如何使用javascript或jquery从url下载文件? [英] how to download a file from url using javascript or jquery?
本文介绍了如何使用javascript或jquery从url下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用了jquery fileDownload插件从URL下载文件.但这不起作用.总是失败,请为此提供帮助
I used jquery fileDownload plugin to download a file from URL. But it's not working. It is always failing please help with this
$.fileDownload(url,{
contentType: "text/csv",
contentDisposition: 'attachment; filename=' +
url.split("/").pop()
})
.done(function(){console.log('successfully downladed')})
.fail(function(){ console.log(`request failed`)});
即使我尝试使用javascript也不起作用
Even I tried with javascript it's not working
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();
推荐答案
您的JavaScript无法正常工作,可能是因为在添加href
和download
属性之前将a
附加到了正文.
Your JavaScript does not work probably because you append a
to body before you add href
and download
attributes.
在触发click
Also remember that this will only work on files with the same-origin URLs (Source).
此属性仅适用于相同来源的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();
这篇关于如何使用javascript或jquery从url下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文