文件下载重命名不起作用 [英] File download rename not working
本文介绍了文件下载重命名不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试重命名具有下载属性的文件,但是它不起作用.
I try to rename file with download attribute but it's not working.
<a href="https://jsfiddle.net/img/logo.png" download="something.png">OK</a>
推荐答案
它仅在文件源相同的情况下才有效,因此,如果您可以使用CORS + ajax下载外部文件,则可以使用自定义名称保存Blob
It only works if the file is on the same origin so if you can download a external file with CORS + ajax then you can save the blob with a custom name
$('a').click(function(evt){
evt.preventDefault();
var name = this.download;
// we need a blob so we can create a objectURL and use it on a link element
// jQuery don't support responseType = 'blob' (yet)
// So I use the next version of ajax only avalible in blink & firefox
// it also works fine by using XMLHttpRequest v2 and set the responseType
fetch("https://crossorigin.me/" + this.href)
// res is the beginning of a request it only gets the response headers
// here you can use .blob() .text() .json or res.arrayBuffer() depending
// on what you need, if it contains Content-Type: application/json
// then you might want to choose res.json()
// all this returns a promise
.then(res => res.blob())
.then(blob => {
$("<a>").attr({
download: name,
href: URL.createObjectURL(blob)
})[0].click();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="https://jsfiddle.net/img/logo.png" download="something.png">OK</a>
这篇关于文件下载重命名不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文