0

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;
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Garo Gabrielyan
  • 466
  • 2
  • 7
  • 20
  • I'm not sure I understand; you're explicitly clicking the link, same as if the user did it. Are you saying you want to initiate a download on the user's browser when the button is clicked? – Dave Newton Sep 01 '22 at 14:44
  • This is a similar question: https://stackoverflow.com/questions/42158040/how-can-i-prevent-href-redirect-onclick To prevent redirects, you can use Event.preventDefault() https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault – pythko Sep 01 '22 at 14:47
  • clicking the link won’t trigger a download if the resource to be downloaded wasn’t served from the same origin or same server, check my below answer – Abasaheb Gaware Sep 02 '22 at 04:35

2 Answers2

1

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

Abasaheb Gaware
  • 509
  • 4
  • 13
0

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

Abasaheb Gaware
  • 509
  • 4
  • 13