Anchor tag with download attribute opens file instead of downloading

后端 未结 2 569
醉话见心
醉话见心 2021-01-17 01:06

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

downloa         


        
相关标签:
2条回答
  • 2021-01-17 01:43

    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.
    0 讨论(0)
  • 2021-01-17 01:54

    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.

    0 讨论(0)
提交回复
热议问题