我正在尝试创建一个google-chrome-extension,它将下载一个mp3文件。我正在尝试使用HTML5 blob和iframe来触发下载,但它似乎不起作用。这是我的代码:
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();
在控制台中查看时,正确创建了blob,设置看起来正确:
尺寸:15312172 键入:“application / octet-stream”
但是,当我尝试createObjectURL()
创建的链接时,
团块:铬扩展:// dkhkkcnjlmfnnmaobedahgcljonancbe / b6c2e829-c811-4239-bd06-8506a67cab04
我收到一份空白文件和一条警告说
资源被解释为Document但是 使用MIME类型转移 应用/八位字节流。
如何让我的代码正确下载文件?
答案 0 :(得分:5)
以下代码适用于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);
答案 1 :(得分:0)
我不确定,但我认为这是您服务器的麻烦。我刚刚尝试了一段代码来下载一些mp3文件的示例blob,一切都很顺利。也许吧: