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

时间:2018-05-23 11:25:58

标签: javascript jquery download jquery-plugins downloadfile

我使用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`)});

即使我尝试使用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();

1 个答案:

答案 0 :(得分:1)

您的JavaScript无效,可能是因为您在添加ahref属性之前将download附加到正文。

在触发click

之前追加

另请注意,这仅适用于具有相同来源网址(Source)的文件。

  

此属性仅适用于same-origin URLs

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();