简体   繁体   中英

Anchor tag with download attribute opens file instead of downloading

In my Reactjs application I used the anchor tag to download a txt file like below.

<a href="http://textfiles.com/......./sample.txt" download>download</a>

There I added download attribute to force it to download instead open it in the browser tab.

But it is still opening in the same tab instead of downloading. Can any one help me to solve this problem.

Looking at your example seems you're not using same origin and that might have cause the problem.

If you're trying to download the file which exists in same origin then I suggest you to use relative url rather than absolute url.

Example:

<a href="/public/sample.txt" download>download</a>

Please take a look at the note from docs :

Attribute: download

Notes:

  • This attribute only works for same-origin URLs .
  • Although HTTP(s) URLs need to be in the same-origin, blob: URLs and data: URLs are allowed so that content generated by JavaScript, such as pictures created in an image-editor Web app, can be downloaded.
  • If the HTTP header Content-Disposition : gives a different filename than this attribute, the HTTP header takes priority over this attribute.
  • If Content-Disposition: is set to inline, Firefox prioritizes Content-Disposition, like the filename case, while Chrome prioritizes the download attribute.

Try like this

import File from 'http://textfiles.com/......./sample.txt'; //Or the path could be any relative path to the local file.

//Other code
render() {
    return(
        //Code
        <a href={File} download>download</a>
    )
}

But inorder to use like this, you should be confident that you will get the file without any issues. Better to download the file and access it from your own directory instead of calling from another server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM