Skip to content Skip to sidebar Skip to footer

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:

Post a Comment for "Javascript Binary File Download, And Ajax File Post Upload In Chrome Extension"