Save File in javascript clientside using utf-8 string

912 views Asked by At

I need to download an image file when user click a download button.

I have the content of the file in utf-8 format returned from the server.

ex: "�PNG IHDR@�v/j�sRGB���gAMA���a pHYs���o�d��IDATx^�� �TՕ�_�~��^>�~��N�M�:/��t�Iw�I^��̜8���I@шH��DC�(*" ..... "

( The exact file string displayed in http://codepen.io/jduprey/details/xbale when I upload the same file in this web site)

Now I need to create the blob of the file and save it in the client side.

I tried FileSaver( https://github.com/eligrey/FileSaver.js) library as follows

var blob = new Blob( [ utfFileString ], { type: 'image/png' }); saveAs(blob, aData.name );

But downloaded files are in incorrect format and and cannot be opened.

Appreciate if someone can help me on this.

Thanks!

1

There are 1 answers

0
Musa On

Png files are not utf-8 encoded, notice all those invalid code sequence replacement characters(�) in the string.
You need to get the data in binary format, such as blob or array buffer. Something like

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if (this.readyState == 4 && this.status == 200){
        ...
        var blob = this.response; //The binary data
        ...
        saveAs(blob, aData.name);
        ...
    }
}
xhr.open('GET', 'path/to/file');
xhr.responseType = 'blob'; // the response will be a blob and not text
xhr.send();