HTML通过链接下载文件

时间:2018-04-17 05:18:51

标签: javascript html download

按链接下载文件不起作用。单击时,它将转到浏览器的下一个选项卡并打开该文件。 Chrome 65版

<a download href="images/download.png">download</a>

5 个答案:

答案 0 :(得分:1)

尝试更改路径,如果路径不准确,则会打开新标签

<a href="/images/download.png" download> Download </a>

进一步参考 https://www.w3schools.com/tags/att_a_download.asp

答案 1 :(得分:0)

使用application/octet-stream

<a href="/images/download.png" download type="application/octet-stream "> Download </a>

它只是这样做!
更多格式:https://www.stubbornjava.com/posts/what-is-a-content-type

答案 2 :(得分:0)

$('a').click(function(e) {
    e.preventDefault();  //stop the browser from following
    window.location.href = 'uploads/file.doc';
});

<a href="withoutscript.html">Download now!</a>

尝试使用jquery或没有jquery代码进行此操作

答案 3 :(得分:0)

也尝试这个,会帮助你

$('.download-file').on('click', function(e) {
    
    // For IE
    if(window.navigator.msSaveOrOpenBlob) {
        var blobObject = new Blob(['<p>Hello world!</p>'], {type : 'text/html'});
        window.navigator.msSaveOrOpenBlob(blobObject, 'somefile.html');
        
        e.preventDefault();
    }
    // For browsers that support the `download` attribute
    else {
        // You could also create the url with `window.URL.createObjectURL`
        // var blobObject = new Blob(['<p>Hello world!</p>'], {type : 'text/html'});
        // this.href = window.URL.createObjectURL(blobObject)
        this.href = 'data:text/html;charset=utf-8,'
            + encodeURIComponent('<p>Hello world!</p>');
    }
    
    
    /* * /
    // Doesn't work, idk. It was an attempt for an IE solution
    // Suggested here: http://stackoverflow.com/a/25179390/796832
    // and here: http://stackoverflow.com/a/25179390/796832
    var bufferIframe = document.createElement('iframe');
    bufferIframe.setAttribute('sandbox', 'allow-same-origin');
    bufferIframe.setAttribute('srcdoc', '<p>Hello world!</p>');
    
    document.body.appendChild(bufferIframe);
    
    bufferIframe.contentWindow.document.open('text/plain', 'replace');
    // Keep jsFiddle from complaining about the `write` using 
    bufferIframe.contentWindow.document['write']('<p>write Hello world!</p>');
    bufferIframe.contentWindow.document.close();
    
    //console.dir(bufferIframe.contentDocument);
    bufferIframe.contentWindow.document.execCommand('SaveAs', true, 'request.bin');
    /* */
    
});
<p>Download a file demo</p>


<a href="http://i.stack.imgur.com/kaxff.png" download="savename.png">Download `download` attribute</a>
<br>
<a href="#0" class="download-file" download="some-file.html">Download via JS</a>
<br>

<hr>

Note:
<ul>
    <li>You could always just add the `Content-Disposition: attachment; filename="somefile.html"`</li>
    <li>You can even add the header in .htaccess: `Header set Content-Disposition "attachment"`</li>
</ul>

供参考https://jsfiddle.net/MadLittleMods/dywbo5vx/

答案 4 :(得分:0)

如果链接路径不正确,下载链接无效,请检查图像路径是否正确?检查后下载链接是否正常工作?