Somputer
Somputer

Reputation: 1283

Javascript download attribute not working when saving image dataUrl

I am using chrome.

This is my code.

var save = document.createElement('a');
save.href = fileURL;
save.download = fileName;
alert(save.download);
save.click();

It works well but it doesn't change the image name. It saves as "download.png".

What is wrong?

Upvotes: 1

Views: 848

Answers (1)

DutGRIFF
DutGRIFF

Reputation: 5223

It would help to see what fileURL and fileName are set to but I am guessing that is your problem. In Firefox and Chrome you have to use the relative path to the image. It will not work on remote images.

MDN says:

In Firefox 20 this attribute is only honored for links to resources with the same-origin.

I have tested this in Chrome and Firefox and it only works if you use the relative path to the image:

 save.href = "images/wonky-download-121938718712348891912.jpg";
 save.download = "coolName.jpg";

I say ralative path because using mysite.com/image.jpg didn't work while image.jpg did.

Update

whatwg.org says:

In cross-origin situations, the download attribute has to be combined with the Content-Disposition HTTP header, specifically with the attachment disposition type, to avoid the user being warned of possibly nefarious activity.

Upvotes: 3

Related Questions