Javascript 从 Blob URL 创建下载链接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6076047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a download link from a Blob URL
提问by Jcs
In a Google chrome extension I am working on, a file is downloaded from a server with an XMLHttpRequest
. This file contains some binary data which are stored in an ArrayBuffer
object. In order to provide the possibility to download this file I am using the createObjectURL
API.
在我正在使用的 Google chrome 扩展程序中,从服务器下载了一个扩展名为XMLHttpRequest
. 该文件包含一些存储在ArrayBuffer
对象中的二进制数据。为了提供下载此文件的可能性,我正在使用createObjectURL
API。
function publish(data) {
if (!window.BlobBuilder && window.WebKitBlobBuilder) {
window.BlobBuilder = window.WebKitBlobBuilder;
}
var builder = new BlobBuilder();
builder.append(data);
var blob = builder.getBlob();
var url = window.webkitURL.createObjectURL(blob);
$("#output").append($("<a/>").attr({href: url}).append("Download"));
}
}
It is working fine; except that the filename is an opaque UUID like 9a8f6a0f-dd0c-4715-85dc-7379db9ce142
. Is there any way to force this filename to something more user-friendly?
它工作正常;除了文件名是一个不透明的 UUID,如9a8f6a0f-dd0c-4715-85dc-7379db9ce142
. 有没有办法强制这个文件名更用户友好?
采纳答案by sergio
I have never tried it before, but it should be possible to create a new File object (which allows you to specify a file name) and write your blob to it. Something along the lines of:
我以前从未尝试过,但应该可以创建一个新的 File 对象(它允许您指定文件名)并将您的 blob 写入其中。类似的东西:
function publish(data, filename) {
if (!window.BlobBuilder && window.WebKitBlobBuilder) {
window.BlobBuilder = window.WebKitBlobBuilder;
}
fs.root.getFile(filename, {
create: true
}, function (fileEntry) {
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function (e) {
console.log('Write completed.');
};
fileWriter.onerror = function (e) {
console.log('Write failed: ' + e.toString());
};
var builder = new BlobBuilder();
builder.append(data);
var blob = builder.getBlob();
fileWriter.write(blob);
}, errorHandler);
}, errorHandler);
}
I think this could work for you.
我认为这对你有用。
回答by rmanna
you can force an arbitrary filename by setting the "download" attribute of your anchor
您可以通过设置锚点的“下载”属性来强制使用任意文件名
see: http://updates.html5rocks.com/2011/08/Downloading-resources-in-HTML5-a-download
见:http: //updates.html5rocks.com/2011/08/Downloading-resources-in-HTML5-a-download