gustavomonteirodev
gustavomonteirodev

Reputation: 25

How to force js in React to Download Files?

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

  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%2F20221111%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20221111T135108Z&X-Amz-SignedHeaders=host&X-Amz-Expires=3600&X-Amz-Signature=9e11f9af9fc1ba81f3100a2da6d29a6fd71e3b5a7a9e5b7682dc5171530b251a', 'image.png')} >Baixar arte gráfica</button>

Please guys, help me, I tried every tutorial on Youtube and here on StackOverflow.

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 StackOverflow, so I put the method I'm using to force it to download and the link I must embebed in my project.

Upvotes: 0

Views: 330

Answers (1)

godo57
godo57

Reputation: 548

Try to encapsulate the button with an <a> element like:

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

Edit thanks to Disco comment:

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

Upvotes: 1

Related Questions