javascript 如何使用javascript或jquery从url下载文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50487199/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:08:30  来源:igfitidea点击:

how to download a file from url using javascript or jquery?

javascriptjquerydownloadjquery-pluginsdownloadfile

提问by bhasker

I used jquery fileDownload plugin to download a file from URL. But it's not working. It is always failing please help with this

我使用 jquery fileDownload 插件从 URL 下载文件。但它不起作用。它总是失败请帮助解决这个问题

$.fileDownload(url,{
    contentType: "text/csv",
    contentDisposition: 'attachment; filename=' + 
        url.split("/").pop()
})
.done(function(){console.log('successfully downladed')})
.fail(function(){ console.log(`request failed`)});

Even I tried with javascript it's not working

即使我尝试使用 javascript 它也不起作用

var a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
fileName = url.split("/").pop();
a.download = fileName
a.click();
window.URL.revokeObjectURL(url);
a.remove();

回答by Krzysztof Janiszewski

Your JavaScript does not work probably because you append ato body before you add hrefand downloadattributes.

您的 JavaScript 不起作用可能是因为您a在添加hrefdownload属性之前附加到正文。

Append just before triggering click

在触发之前追加 click

Also remember that this will only work on files with the same-origin URLs (Source).

还请记住,这仅适用于具有同源 URL ( Source) 的文件。

This attribute only works for same-origin URLs.

此属性仅适用于同源 URL

var a = document.createElement("a");
a.href = url;
fileName = url.split("/").pop();
a.download = fileName;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
a.remove();