使用chrome扩展中的html5 blob下载mp3文件

Fra*_*yer 4 javascript html5 blob google-chrome-extension

我正在尝试创建一个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();
Run Code Online (Sandbox Code Playgroud)

在控制台中查看时,正确创建了blob,设置看起来正确:

大小:15312172类型:"application/octet-stream"

但是,当我尝试创建的链接时createObjectURL(),

BLOB:铬扩展:// dkhkkcnjlmfnnmaobedahgcljonancbe/b6c2e829-c811-4239-bd06-8506a67cab04

我收到一份空白文件和警告说

资源解释为Document但使用MIME类型application/octet-stream传输.

如何让我的代码正确下载文件?

小智 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);
Run Code Online (Sandbox Code Playgroud)