File API not working with Blob in Google Chrome Extension
-
05-06-2021 - |
Question
I'm writing an extension for Google Chrome where I need to download the images of a page and save them on disk on temporary files. To do this, I make an XMLHttpRequest and use it to download the image. In the callback function, when I have the image in request.response, I request a temporary file from Windows using window.webkitRequestFileSystem(window.TEMPORARY, 1024 * 1024 * 20, writeImageToFile, errorHandler)
. In the callback function writeImageToFile, I create the FileWriter object and write the blob into it. The file is getting created but I'm not able to find out where it is being created. I need the windows path of the file for the extension. Please help!
Solution
For your purpose, you do not need a virtual file system. Use the webkitURL.createObjectURL
method to create a URL from a blob:
window.webkitURL.createObjectURL(blob);
Since Chrome 19, you can directly get a Blob
object using responseType
:
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
// xhr.response is a Blob
var url = webkitURL.createObjectURL(xhr.response);
console.log('URL: ', url);
};
xhr.open('GET', 'http://example.com/favicon.ico');
xhr.send();
Since Chrome 10, you can get an ArrayBuffer
response, and convert it to a blob (demo):
var xhr = new XMLHttpRequest();
xhr.responseType = 'arraybuffer';
xhr.onload = function() {
// Create blob from arraybuffer
var bb = new (window.BlobBuilder || window.WebKitBlobBuilder)();
bb.append(xhr.response);
var url = webkitURL.createObjectURL(bb.getBlob());
console.log('URL: ', url);
};
xhr.open('GET', 'http://example.com/favicon.ico');
xhr.send();
(Use window.URL
and MozBlobBuilder
if you want to use the same code for Firefox).