Sending tab screenshots to a remote server from a firefox addon - javascript

I have firefox addon (made using the firefox addon sdk) which when instructed takes a screenshot of the currently active tab and sends it in an ajax request to a remote server.
The following code in addon-script main.js is responsible for taking getting the thumbnail
var tab_image_data=tabs.activeTab.getThumbnail();
var tab_image_data = base64.encode(tab_image_data);
panel.port.emit("screenshot",{image_data:tab_image_data});
The image data generated by the function getThumbnail() is sent to a content script file belonging to a panel.
In the content script the following code is responsible for sending the image data to the server
var tab_image_data=addonmessage.image_data;
var myBlob = new Blob([tab_image_data], { "type" : "text/base64data"} );
var formData = new FormData();
formData.append('img',myBlob);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://xyz.abc.com/imageshot/index.php", true);
xhr.onload = function() {
if (xhr.status == 200) {
console.log('all done: sq');
} else {
console.log('Nope');
}
};
xhr.send(formData);
Everything works fine and the image file is created on server in jpeg format. But when I try to view that image, the windows photo viewer gives a not supported file format error.
I tried to base64 encode the data before sending it but that did not work as well. Suprisingly I have a chrome extension that performs a similar function and that works flawlessly. In both cases the same php script is being used on the server side.
Any help regarding this matter will be highly appreciated
Thanks in advance.

Related

IE + XMLHttp + CreateObjectURL Error

I am trying to download and show the contents of a remote file inside an iFrame , and succeeded in all browsers except for IE(i am trying with IE 10).
I have used XMLHttpRequest,Blob,CreateOBjectUrl APIs to complete the process.
In IE i am not able to view the file content inside the iFrame and also no particular error messages appeared on console as well.
I had pasted my code at the bottom of this thread , and a step by step explanation as below
Getting the download document url & corresponding mime
type(Perfectly fine in all broswers).
Invoking XMLHttp Request , a
Http GET Async call ,as response type as 'arraybuffer' (Perfectly
fine in all browsers) Upon completing the XMLHttpGet below 3 steps are
executing.
Creating a blob using the proper mimetype ;(Perfectly fine in all other browsers, specially verified the blob by downloading it in IE using MSSaveOrOpenBlob method).
4.InOrder to bind the blob contents to the iFrame , create the blob url using "createObjectURL" (Perfectly fine in all browsers , but in IE we are not getting a perfect URL).
Finally binding the URL with the iFrame for display.
Code snippet below.
// Getting the document url and mime type ( Which is perfectly fine )
var downloadUrl=finalServerURL + "DocumentService.svc/GetItemBinary?id=" + itemId + "&version=" + version;
var mimeTypeForDownload = responseStore.mimeTypes[currentlySelectedObject.fileExtension];
window.URL = window.URL || window.webkitURL;
//Defining the XML Http Process
var xhr = new XMLHttpRequest();
xhr.open('GET', downloadUrl, true);
xhr.responseType = 'arraybuffer'; //Reading as array buffer .
xhr.onload = function (e) {
var mimeType = mimeTypeForDownload;
var blob = new Blob([xhr.response], { type: mimeType });
// Perfect blob, we are able to download it in both IE and non-IE browsers
//This below url from createObjectURL,
//Working perfectly fine in all non-IE browsers, but nothing happening in IE
var url = window.URL.createObjectURL(blob);
document.getElementById(documentContentiFrameId).setAttribute("src", url);
};
xhr.send;
Please let me if you get any information on this , would be really helpful.
I came to know that its not possible in IE to get a proper URL for your blob entries , none of my attempts are get succeeded.
My alternative solutions,
1)go for pdf.js , an open source javascript library , which allows to render pdf binaries and equivalent pdf blobs.
2)Write your own viewers by utilizing the open PDF libraries , which will be time consuming , and more learning efforts involved.
Thanks,
Vishnu

AJAX Upload file straight after downloading it (without storing)

I'm making a JavaScript script that is going to essentially save an old game development sandbox website before the owners scrap it (and lose all of the games). I've created a script that downloads each game via AJAX, and would like to somehow upload it straight away, also using AJAX. How do I upload the downloaded file (that's stored in responseText, presumably) to a PHP page on another domain (that has cross origin headers enabled)?
I assume there must be a way of uploading the data from the first AJAX request, without transferring the responseText to another AJAX request (used to upload the file)? I've tried transferring the data, but as expected, it causes huge lag (and can crash the browser), as the files can be quite large.
Is there a way that an AJAX request can somehow upload individual packets as soon as they're recieved?
Thanks,
Dan.
You could use Firefox' moz-chunked-text and moz-chunked-arraybuffer response types. On the JavaScript side you can do something like this:
function downloadUpload() {
var downloadUrl = "server.com/largeFile.ext";
var uploadUrl = "receiver.net/upload.php";
var dataOffset = 0;
xhrDownload = new XMLHttpRequest();
xhrDownload.open("GET", downloadUrl, true);
xhrDownload.responseType = "moz-chunked-text"; // <- only works in Firefox
xhrDownload.onprogress = uploadData;
xhrDownload.send();
function uploadData() {
var data = {
file: downloadUrl.substring(downloadUrl.lastIndexOf('/') + 1),
offset: dataOffset,
chunk: xhrDownload.responseText
};
xhrUpload = new XMLHttpRequest();
xhrUpload.open("POST", uploadUrl, true);
xhrUpload.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhrUpload.send(JSON.stringify(data));
dataOffset += xhrDownload.responseText.length;
};
}
On the PHP side you need something like this:
$in = fopen("php://input", "r");
$postContent = stream_get_contents($in);
fclose($in);
$o = json_decode($postContent);
file_put_contents($o->file . '-' . $o->offset . '.txt', $o->chunk);
These snippets will just give you the basic idea, you'll need to optimize the code yourself.

cannot upload files and vars with xhr2 and web workers

I try to create code to upload files using XHR2 and web workers.
I thought I should use web workers , so if a file is big, web page will not freeze.
This is not working for two reasons, I never used web workers before, and I want to post to the server the file and vars at the same time, with the same xhr. When I say vars I mean the name of the file, and an int.
Heres is what I got
Client side
//create worker
var worker = new Worker('fileupload.js');
worker.onmessage = function(e) {
alert('worker says '+e.data);
}
//handle workers error
worker.onerror =werror;
function werror(e) {
console.log('ERROR: Line ', e.lineno, ' in ', e.filename, ': ', e.message);
}
//send stuff to the worker
worker.postMessage({
'files' : files, //img or video
'name' : nameofthepic, //text
'id':imageinsertid //number
});
Inside the worker (fileupload.js file)
onmessage = function (e) {var name=e.data.name; var id=e.data.id ; var file=e.data.files;
//create a var to catch the anser of the server
var datax;
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status == 200) {datax=xhr.response;}
else { datax=525;}//actually, whatever, just give a value
};
xhr.open('POST', 'upload.php');
xhr.send(file,name,id);
//i also tried xhr.send('file=file&name=name&id=id'); and still nothing
//i also tried just the text/int xhr.send('name=name&id=id'); and still nothing
I am confused. I cannot send anything to the server. I get no feedback from the worker. I dont even know if the data are send to the fileupload.js. Server side does not INSERT.
Is that possible, sending files and text at the same time? What am I missing?
I need to pass text and int along with the file, so server side not only will upload the file, but also will INSERT to the database the int and the text, if the file is uploaded succesfully. This was easy just with formData and xhr, but, putting web workers in the middle, I cant get it right.
Also, can I use Transferable Objects to speed things up? Are Transferable Objects supported in all major browsers?
Thanks in advance

save blob audio file on server with xmlhttprequest

I'm working on an audio web application where you can play along with music and record yourself. I'm working with a recorder plugin and I'm trying to save what has been recorded in a folder on a server. I get a blob file from the plugin via this javascript code:
recorder.exportWAV(function(blob) {
var xhr = new XMLHttpRequest();
var url = '../../audio/recordings/test.wav';
xhr.open('POST',url,true);
xhr.onload = function(e) {
if (this.status == 200) {
console.log(this.responseText);
}
};
xhr.send(blob);
},'audio/wav');
I have never worked with this before so I'm not sure if my code is right. But I get no errors my file is just not saved. I have been searching the internet for this and what I have found is that a lot of people use a php file as url. Why? What php file are they using?
Thanks!

How to upload a binary file in IE8 then send it to server using xmlhttprequest

I'm working on the web pages of an embeded device. To exchange data between the web page and the application of this device I use xmlhttprequest.
Now I search a way to allow the client to upload a binary (to update the firmware of that device) to the server.
One big limitation : it needs to works in IE8 (a cross browser solution would be ideal, but it's mandatory to work on IE8 first...)
In detail what I have to do :
Use the <input type='file'> to select the file on the client computer
Send the file (using xmlhttprequest?) to the server
The server will reassemble the file and to whatever it need to do with it...
I was able to get a binary from the client to the server in chrome, but in IE8, my method was not compatible.
The relevant html file :
<input id="uploadFile" type="file" />
In the javascript, I tried different way to fire an event with the input file type
// does not work in IE8 (get an Obj doesnt support this property or method)
document.querySelector('input[type="file"]').addEventListener("change"),function(e)...
// tried with jQuery, does not work in IE8(I may not using it correctly...)
$('upload').addEvent('change', function(e)....
$('upload').change(function(e)....
So my first problem is : how to do a onChange event with the input type file in IE8?
Also the method I was using in chrome (found on this page : http://www.html5rocks.com/en/tutorials/file/xhr2/ ) but that is not working on IE8 :
function upload(blobOrFile) {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/server', true);
xhr.onload = function(e) { ... };
xhr.send(blobOrFile);
}
document.querySelector('input[type="file"]').addEventListener('change', function(e) {
var blob = this.files[0];
const BYTES_PER_CHUNK = 1024 * 1024; // 1MB chunk sizes.
const SIZE = blob.size;
var start = 0;
var end = BYTES_PER_CHUNK;
while(start < SIZE) {
upload(blob.slice(start, end));
start = end;
end = start + BYTES_PER_CHUNK;
}
}, false);
})();
Because the document.querySelector generate an error in IE8, I don't know if the rest of this code works in IE8 (I wish it can works!)
Any help and suggestion will be greatly appreciated!!!

Categories