文件下载重命名不起作用

You*_*sef 0 html html5 google-chrome

我尝试使用下载属性重命名文件,但它无法正常工作.

<a href="https://jsfiddle.net/img/logo.png" download="something.png">OK</a>
Run Code Online (Sandbox Code Playgroud)

小提琴

Sla*_*anX 5

来自您链接的文档:

如果HTTP标头Content-Disposition:存在并提供与此属性不同的文件名,则HTTP标头优先于此属性.

我的猜测是你链接的服务器设置了这个标题.

此外,如果您链​​接到外部资源,它可能无法正常工作:

此属性仅适用于具有相同来源的资源的链接.


End*_*ess 5

它仅在文件位于同一源时才有效,因此如果您可以使用CORS + ajax下载外部文件,则可以使用自定义名称保存blob

$('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();
        });
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)