在 chrome 扩展中使用 html5 blob 下载 mp3 文件
我正在尝试创建一个 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 type: "application/octet-stream"
但是,当我尝试使用 createObjectURL()
创建的链接时,
blob:chrome-extension://dkhkkcnjlmfnnmaobedahgcljonancbe/b6c2e829-c811-4239-bd06-8506a67cab04
我收到一个空白文档和一条警告说
资源解释为文档,但 以 MIME 类型传输 应用程序/八位字节流。
如何让我的代码正确下载文件?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下代码在 Google chrome 14.0.835.163 中对我有用:
The below code worked for me in Google chrome 14.0.835.163:
我不确定,但我认为这是你的服务器的问题。我刚刚尝试了您的代码来下载一些 mp3 文件示例 blob,一切正常。所以也许:
I'm not sure, but i think this is your server's trouble. I've just tried your piece of code to download some sample blob of mp3-file and everything went ok. So maybe: