Home > Software design >  How to force javascript in React to Download image?
How to force javascript in React to Download image?

Time:11-12

Using just HTML is not possible. I need to download using a callback function, but it's not working.

I need to encapsulate the button with an element like:

<a href="https://path.to.your.file.com" target="_blank" rel="noreferrer">
  <button>Click</button>
</a>

I need to create a callback function:

 const downloadImage = ( dataURL: string, fileName: string ) => {
    const link = document.createElement('a')
    link.download = fileName
    link.href = dataURL
    link.click()
  }

Return:

 <button className="btn btn-primary btn-sm" onClick={() => downloadImage('https://estica-public.s3.amazonaws.com/21965/conversions/8b3ujv9ze8d0uho287bq182zgpvv-full.png?X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAY2EWNM3MQCGRS66O/20221111/us-east-1/s3/aws4_request&X-Amz-Date=20221111T135108Z&X-Amz-SignedHeaders=host&X-Amz-Expires=3600&X-Amz-Signature=9e11f9af9fc1ba81f3100a2da6d29a6fd71e3b5a7a9e5b7682dc5171530b251a', 'image.png')} >Baixar arte gráfica</button>

I tried html method, using labs, but I really need to do this code works, someone please could help me? I already tried every method here on Stack Overflow, so I put the method I'm using to force it to download and the link I must embed in my project.

CodePudding user response:

https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/downloads/download

Have a look in that doc. There everything is explained.

CodePudding user response:

function downloadImage(url, name = 'newImage') {
    return fetch(url)
        .then(resp => resp.blob())
        .then(blob => {
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = name;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);

            return Promise.resolve();
        })
}

function download() {
    downloadImage('https://picsum.photos/536/354', 'newFileName')
      .then(() => console.log('ok'))
      .catch(() => console.log('error'))
}
<div onClick="download()">download click</div>

  • Related