【发布时间】:2016-08-02 06:29:34
【问题描述】:
我想使用 javascript 或 jquery 自动下载文件 下面是我正在使用的代码,但该代码以新的方式打开文件 浏览器中的选项卡不会下载到磁盘中。
function SaveToDisk(fileUrl, fileName) {
var hyperlink = document.createElement('a');
hyperlink.href = fileUrl;
hyperlink.target = '_blank';
hyperlink.download = fileName || fileUrl;
(document.body || document.documentElement).appendChild(hyperlink);
hyperlink.onclick = function() {
(document.body || document.documentElement).removeChild(hyperlink);
};
var mouseEvent = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
hyperlink.dispatchEvent(mouseEvent);
// NEVER use "revoeObjectURL" here
// you can use it inside "onclick" handler, though.
// (window.URL || window.webkitURL).revokeObjectURL(hyperlink.href);
// if you're writing cross-browser function:
if(!navigator.mozGetUserMedia) { // i.e. if it is NOT Firefox
window.URL.revokeObjectURL(hyperlink.href);
}
}
SaveToDisk('http://example.com/service/getUserImage/339/256', 'image.png');
【问题讨论】:
标签: javascript jquery download