Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

javascript - Downloading mp3 files using html5 blobs in a chrome-extension

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...