I'm using javascript and html canvas to resize jpeg images. After resizing, I use canvas.toDataURL
as the href attribute in an anchor tag in order to provide a link where users can download the resized images.
This works nicely up to a certain image size.
It seems that different browsers have different limits on the size of data urls as mentioned here: https://developer.mozilla.org/en-US/docs/Web/HTTP/data_URIs
In chrome, when I'm over the data url size limit, nothing happens when I click on the download link; no errors or anything (as far as I can tell).
Is there a some way to programmatically detect whether a data url is too large? Maybe some browser event that will show me whether clicking a download link failed?
Ideally, I'd like to detect whether the download was successful. When data urls are too large, I'd like to display an explanation to the end user describing how to right click on the image and choose "save as ...", which always seems to work.
Update 1:
It looks like using canvas.toBlob
is the best workaround for now. Here's the api documentation: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob.
Here's a jsfiddle that demonstrates how anchor href download links fail when using toDataURL
for larger canvases, but toBlob
seems to work:
https://jsfiddle.net/upgradingdave/c76q34ac/3/
Here are some related stackoverflow questions: canvas.toDataURL() download size limit
console.log(theDataURL.length)
report zero length or something else? – MoatstheDataURL.length
returns the correct length even when the download fails, unfortunately. – Harned<a>
(the image loads fine but I get an uncatchable "Network Error" when using the download). What I would do is to play the safety by always converting your dataURI to a blob (or even better callcanvas.toBlob()
when available) and set the anchor'shref
to an objectURL. You shouldn't have this limitations. (I just tried with a 126MB output file and it works) – Caverncanvas.toBlob()
. Thanks! – HarnedtoBlob
is the best workaround. I added a jsfiddle. If you want to add an answer suggesting to use toBlob, I'll mark it as accepted. Thanks again. – Harned