Home > Net >  How can I download an image using React?
How can I download an image using React?

Time:09-02

I'm trying to download files by URL, but the page is redirecting instead of downloading.

I don't want to use any extensions or libraries.

    const File = ({href}) => {
            const onDownload = () => {
                    const link = document.createElement('a');
                    link.href = href;
                    link.download = 'name';
                    link.click();
                }
            return (
                <button onClick={onDownload}>
                    download
                </button>
            );
        };
    
    const Downloader = () => {
        const files = [
            'https://thumbs.dreamstime.com/b/example-red-tag-example-red-square-price-tag-117502755.jpg',
            'https://image.shutterstock.com/image-photo/example-word-written-on-wooden-260nw-1765482248.jpg',
        ]
    
    
        return (<div>{files.map(f => <File href={f} key={f}/>)} </div>);
    };
    
    export default Downloader;

CodePudding user response:

you can simply add this in place of a button:

const File = ({href}) => {
    return (
            <a href={href} download><button>Download</button></a>
    );
};

This will force the browser to download the link file

CodePudding user response:

As of late 2018, clicking the link won’t trigger a download if the resource to be downloaded wasn’t served from the same origin or same server. Apparently, this is restriction is a security measure.

You can download the content in browser and make it downloadable, you can check the below url:

https://medium.com/charisol-community/downloading-resources-in-html5-a-download-may-not-work-as-expected-bf63546e2baa

answer from this: Download Link not working in html

  • Related