Javascript Binary File Download, And Ajax File Post Upload In Chrome Extension
I'm writing a chrome extension content script which will embed itself on some pages, and when there are certain file type links (.doc, .torrent, etc) it will download that file, an
Solution 1:
Your upload method does not work, because all binary characters are encoded as UTF-8. I posted the explanation and solution in an answer at this question.
In your case, you don't need to manually create the post data. Request the initial data in a smart way, and use the FormData
object to post the binary data. For instance:
var x = newXMLHttpRequest();
x.onload = function() {
// Create a formvar fd = newFormData();
fd.append("upfile", x.response); // x.response is a Blob object// Upload to your servervar y = newXMLHttpRequest();
y.onload = function() {
alert('File uploaded!');
};
y.open('POST', 'http://python/server/');
y.send(fd);
};
x.responseType = 'blob'; // <-- This is necessary!
x.open('GET', 'http://foo.com/bar.torrent', true);
x.send();
Note: I replaced false
with true
at the initial request. Avoid using synchronous XMLHttpRequest
when it's also possible to asynchronously create the request.
If you don't understand the answer, here are more examples with thorough explanations:
- XMLHttpRequest: Multipart/Related POST with XML and image as payload -
FormData
is not used, but the post data is manually created instead. - Upload a File in a Google Chrome Extension - A sample Chrome extension which uses Web Workers (with a FormData polyfill) to upload files
- Google chrome rehost image extension - Scrapes an image from the page, and upload the image to imgur using a Chrome extension.
Post a Comment for "Javascript Binary File Download, And Ajax File Post Upload In Chrome Extension"