문제

I use this code to save images in Javascript :

window.location.href = grid.toDataURL("image/png").replace("image/png", "image/octet-stream");

The code works, but the file saved doesn't have any extension, I have to rename it manually.

My question is how can I put the extension at the end ?

Thank you.

도움이 되었습니까?

해결책

toDataURL produces a data-uri not a file name so extensions doesn't apply in this case.

A data-uri is simply a text encoded version of the binary content which some browsers can read as a file - a data-stream if you will. As data streams doesn't have any filename you can't attach one.

You can work around this by setting an anchor tag like this:

<a id="imageLink" href="data-uri-here" download="myFilename.png">
    Click to download
</a>

In JavaScript you can set these attributes dynamic:

imageLink.href = grid.toDataURL();
imageLink.download = 'myOtherFilename.png';
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top