JQuery自定义文件名/类型

时间:2016-12-09 22:56:04

标签: jquery

所以我创建了这个JQuery脚本,我不知道如何更改文件类型(.png,.jpg等)和名称。这是一个预览:

jQuery('<a/>', {
    id: 'downloadFile',
    href: 'https://www.roblox.com/asset/?id='+location.href.match(/(?:catalog|library|games)\/(\d+)/i)[1], // Don't mind the link
    style: 'display:hidden;',
    download: ''
}).appendTo('body');

$("#downloadFile")[0].click();

是的,我想是的。回复总是有帮助的。

1 个答案:

答案 0 :(得分:0)

如果服务器响应包含Access-Control-Allow-Origin标头,您可以使用fetch()来请求资源,Response.blob()Blob作为响应。将Blob响应作为第一个参数传递给File构造函数集.name.type第二个和第三个参数。

使用URL.createObjectURL()对象作为参数创建File的变量引用值,将download属性设置为File.name,设置href a元素到变量引用Blob URL。在click a元素处.one()使用focus附加windowBlob URL事件来调用URL.revokeObjectURL()Blob URL的传递引用从内存中释放// fetch `.txt` file, // change file `.name` set `MIME` type to and download as `.json` let url = "https://gist.githubusercontent.com/guest271314/" + "02d250fe055f6f7e4742221ed2b2db7f/raw/" + "91c06caaa0944fc2cf6bcd335f0320c6de837a9c/arr.txt"; fetch(url) .then(response => response.blob()) .then(blob => { let file = new File([blob], "file.json" , {type: "application/json", lastModified: new Date().getTime()}); console.log(file.type, file.name); let blobURL = URL.createObjectURL(file); jQuery('<a/>', { id: 'downloadFile', href: blobURL, style: 'display:hidden;', download: file.name }).appendTo('body') .on("click", function() { $(window).one("focus", function() { URL.revokeObjectURL(blobURL) }) })[0].click(); })

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
ul, li, a {
  position: relative;
  display: inline-block;
  margin: 0 0 5px 0;
}
ul {
  white-space: nowrap;
}
li {
  padding: 0 5px;
}
li:after {
  content: '';
  position: absolute;
  left: 0;
  width: 100%;
  height: 5px;
  bottom: -12px;
  border-top: 1px solid #a2a2a2;
  border-bottom: 1px solid #a2a2a2;
}
li:hover:after {
  border-top: 0px solid #a2a2a2;
}