开发者

How do I force download with HTML/JavaScript?

I have a link and, if a user clicks it, I need 2 things to happen:

  • A proper HTTP response is sent to the user (especially with Content-Type: video/mp4)
  • and a video file will automatically begin downloading.开发者_如何学C

I have seen something of the sort with PHP, but is it possible only with HTML/JavaScript?


you can use the download attribute

<a href="http..." download></a>

or specify a filename using

<a href="http..." download="filename.pdf"></a>

see more: https://developer.mozilla.org/en/HTML/element/a#attr-download


Automatically will depend a lot on the browser and its options. But you can tell the browser what you want to have happen (which it will then double-check with the user) via the Content-Disposition header in the response. For instance, setting it to attachment;filename=blah.mp4 will, on most browsers, invite the user to download it (using that filename) even if normally the browser would have tried to display/play the content in its own interface. See the link for details. (Downloading is probably the default for mp4 files, but that's up to the user; I find this helpful when offering download links for HTML files.)

You can set the header via configuration in your web server if you're not using server-side scripting (as you've said you're not). For instance, with Apache you'd use a rule matching the URL for these video files and use the Header directive.


No, this is not possible (at least for values of JavaScript limited to client-side JavaScript).

If you want to override the default behavior of how a browser handles an HTTP resource, you need to do it with HTTP headers. If you want to do it correctly, use the content-disposition header (with an attachment value).

You can set this header using server-side JavaScript or (pretty much) any other server side environment.


I found a reliable way of forcing a download using the library Axios

<script src=
"https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
<button onclick="download()">Download</button>
<script>
    let downloadUrl  = 'https://example.com/image.jpg';
    let downloadName = 'image.jpg';
    function download(){
        axios({
            url: downloadUrl,
            method:'GET',
            responseType: 'blob'
        })
        .then((response) => {
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', downloadName);
            document.body.appendChild(link);
            link.click();
        });
    }        
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜