1

I am downloading an image when a div is clicked by using...

document.location.href = save_canvas.toDataURL("image/jpeg").replace("image/jpeg", "image/octet-stream");

This is working but the image that downloads has no extension and is just called 'download'

I have tried setting the name like this...

document.location.download = "myfile.jpg";
document.location.href = save_canvas.toDataURL("image/jpeg").replace("image/jpeg", "image/octet-stream");

But it is having no effect, where am i going wrong?

fightstarr20
  • 11,682
  • 40
  • 154
  • 278

1 Answers1

1

The download attribute is not part of the Location object as document.location holds, only for the HTML anchor (A) tags (except in IE).

Depending on browser and version you could instead try to convert canvas into a Blob object, then to File in order to set a filename, and serve that as URL via URL.createObjectURL(). Also here, toBlob() is not supported in IE (but you can polyfill toBlob(), and use msSaveBlob instead).

(and you would also want to replace mime-type's "image" with "application" for mime-type (e.g. "application/octet-stream"). )

c.toBlob(function(blob) {
  var file = new File([blob], "test.png", {type: "application/octet-stream"});
  document.location.href = URL.createObjectURL(file);
})
A save request with PNG and filename should appear when running this code...
<canvas id=c></canvas>

Optionally, try the FileSaver.js library which deals with many special cases.