Downloading mp3 files using html5 blobs in a chrome-extension
blob, google-chrome-extension, html, javascript
Solution
The below code worked for me in Google chrome 14.0.835.163:
var finalURL = "http://localhost/Music/123a4.mp3";
var xhr = new XMLHttpRequest();
xhr.overrideMimeType("application/octet-stream");
//xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.open("GET", finalURL, true);
xhr.responseType = "arraybuffer";
xhr.onload = function() {
var bb = new (window.BlobBuilder || window.WebKitBlobBuilder)();
var res = xhr.response;
if (res){
var byteArray = new Uint8Array(res);
}
bb.append(byteArray.buffer);
var blob = bb.getBlob("application/octet-stream");
var iframe = document.createElement("iframe");
iframe.style.display = "none";
iframe.src = window.webkitURL.createObjectURL(blob);
document.body.appendChild(iframe);
};
xhr.send(null);
Problem
I am trying to create a google-chrome-extension that will download an mp3 file. I am trying to use HTML5 blobs and an iframe to trigger a download, but it doesn't seem to be working. Here is my code: ``` var finalURL = "server1.example.com/u25561664/audio/120774.mp3"; var xhr = new XMLHttpRequest(); xhr.open("GET", finalURL, true); xhr.setRequestHeader('Content-Type', 'application/octet-stream'); xhr.onreadystatechange = function() { if(xhr.readyState == 4 && xhr.status == 200) { var bb = new (window.BlobBuilder || window.WebKitBlobBuilder)(); bb.append(xhr.responseText); var blob = bb.getBlob("application/octet-stream"); var saveas = document.createElement("iframe"); saveas.style.display = "none"; saveas.src = window.webkitURL.createObjectURL(blob); document.body.appendChild(saveas); delete xhr; delete blob; delete bb; } } xhr.send(); ``` When looked in the console, the blob is created correctly, the settings look right: size: 15312172 type: "application/octet-stream" However, when I try the link created by the `createObjectURL()`, blob:chrome-extension://dkhkkcnjlmfnnmaobedahgcljonancbe/b6c2e829-c811-4239-bd06-8506a67cab04 I get a blank document and a warning saying Resource interpreted as Document but transferred with MIME type application/octet-stream. How can get my code to download the file correctly?