Prem
Prem

Reputation: 5987

How to download image inline instead of `save image as` using html/javascript

I am trying to download image in the same window instead of asking the end user to use save-image-as or Ctrl+S in react.js.

The following function is written in the Stateful Class.

forceDownload(event){
    alert(event.target.getAttribute('value'));
    var link = document.createElement('a');
    link.download = 'Download.jpg';
    document.body.appendChild(link);
    link.href = event.target.getAttribute('value');
    link.click();
}

The following code is written in render part

<a value={imageUrl} onClick={this.forceDownload}>Download</a>

The solution works fine only when the alert throws null instead of the actual imageUrl. Is there anything missed out?

Upvotes: 2

Views: 463

Answers (1)

CodeZombie
CodeZombie

Reputation: 2087

create a blob and convert it into downloadable link.

forceDownload(event){
    const data = event.target.getAttribute('value');
    const url = window.URL.createObjectURL(new Blob([data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'quote.pdf');
    document.body.appendChild(link);
    link.click();
}

Upvotes: 2

Related Questions