Save File in javascript clientside using utf-8 string - javascript

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!

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();

Related

Convert in to FileObject from imageUrl using Javascript( on any JS frameworks mostly React)

I do have image url handy , probably an drop box url
https://www.dropbox.com/s/tcg73i4bxbu423g/gradient-test.jpg?dl=0
How to get the fileobject for the same , since my backend api accept only file object , is there any way i can get file object.
I am expecting the below object format . is there any way guys
it will be great if any fiddle is applicable
Note: is it possible to convert without any external api .
any answers will be highly helpful & thankful
You can load image as a file use below function(link, #HaNdTriX). And the url you provided is not an image url so you should extract the image path first.
function toDataUrl(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
imagepath = "https://uc5d3934b120724e8be5a303a2af.previews.dropboxusercontent.com/p/thumb/AA2-rSW7gi7La52QQXPE_mXgt-ssFnHje-5SnLKNxXuTD_qtYtjackFxZTyn3SWQDCLEw66TdZeqa4hMdd33pGxoaXMufvP5XVRPlGZr_a8WJ_OgxphXn45cTKbFHXD2e7I4PcYgSnkBOiYpfqNK_GcMJvTlZskkWvsUwiqopClEkh_4_GDNQcOE-Po8puDE9koQuMnAh6q0Ig4-eZ3xyZO_X-fC9Z9M7niTHGbLAgpVlYWyyKLGFpgVJHD8jpZ1F38c2V8H8M6c4emhMaWr1bEBo4WWxjFHThLj1f1vDrWEv7Z18ZEro-bekrZRh_AwH7oxIBmYFZYhA91c6OMXAFiCdOX0hwRwhMJVxruschBy8bHqVkm2II5wTnDj6IbGlu5uatEt6LVVbLv0U2ZGlmSq/p.jpeg?fv_content=true&size_mode=5"
toDataUrl(imagepath, function(myBase64) {
console.log(myBase64); // myBase64 is the base64 string
});

Saving an Image Blob

I have a function that allows me to pass file content, name, and type and the function will automatically save it. It works great for text based documents, but now I'm trying to have it save other files, like an image file. Somewhere along the line its getting corrupted and isn't working.
function write(text, filename, mime){
var file = new Blob([text], {type:mime}), a = document.createElement('a');
// Download in IE
if(window.navigator.msSaveBlob) window.navigator.msSaveBlob(file, filename);
// Download in compliant browsers
else{
var url = URL.createObjectURL(file);
a.href = url, a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function(){
document.body.removeChild(a);
window.URL.revokeObjectURL(url);}, 0);}}
write('Plain text', 'demo.txt', 'text/plain');
write(atob('iVBORw0KGgoAAAANSUhEUgAAAAEAAAAdCAIAAADkY5E+AAAAD0lEQVR42mNg0AthoDMGAE1BDruZMRqXAAAAAElFTkSuQmCC'), 'demo.png', 'image/png');
FileSaver.js a very powerfull js script to save any type of blob file.
Import it then use it like that:
saveAs(new Blob([file], {type:mime}),filename);
Are you fetching the file using ajax? if so, you should set
XmlHttpRequest.responseType to 'arraybuffer' or 'blob' (default is '' and that will not work with binaries or blob data).
Working example (using arraybuffer) (Fiddle):
var xhr = new XMLHttpRequest();
var url = 'https://upload.wikimedia.org/wikipedia/commons/d/da/Internet2.jpg';
xhr.responseType = 'arraybuffer'; //Set the response type to arraybuffer so xhr.response returns ArrayBuffer
xhr.open('GET', url , true);
xhr.onreadystatechange = function () {
if (xhr.readyState == xhr.DONE) {
//When request is done
//xhr.response will be an ArrayBuffer
var file = new Blob([xhr.response], {type:'image/jpeg'});
saveAs(file, 'image.jpeg');
}
};
xhr.send(); //Request is sent
Working example 2 (using blob) (Fiddle):
var xhr = new XMLHttpRequest();
var url = 'https://upload.wikimedia.org/wikipedia/commons/d/da/Internet2.jpg';
xhr.responseType = 'blob'; //Set the response type to blob so xhr.response returns a blob
xhr.open('GET', url , true);
xhr.onreadystatechange = function () {
if (xhr.readyState == xhr.DONE) {
//When request is done
//xhr.response will be a Blob ready to save
saveAs(xhr.response, 'image.jpeg');
}
};
xhr.send(); //Request is sent
I recommend FileSaver.js to save the blobs as files.
Useful links:
XmlHttpRequest Standard
XmlHttpRequest Standard (responseType attribute)
MDN Docs (XmlHttpRequest)
MDN Docs (ArrayBuffer)

Is it possible to convert any type (Url) to base64 format

I have a link, which can return any type of file (say image/jpeg, zip, mp4 etc).
Now i want to convert the above mentioned file data into base64.
Is it possible with javascript alone ?
I tried canvas.toDataUrl(), but that can help only if my returning file format is image.
Minimal example:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
//the file has been loaded as responseText in xhr
alert(btoa(this.responseText));
}
}
//download video file
xhr.open("someVideo.mpg", "get", true);
xhr.send();

Converting pdf(encoding:UniJIS-UCS2-H) to base64

I have a pdf with encoding UniJIS-UCS2-H. i want to convert it in to base 64 in javascript.
i wrote the code like this. It converting it in to pdf but the content is not visible.
my code is showing below.
function getBinary(file){
var xhr = new XMLHttpRequest();
xhr.open("GET", file, false);
xhr.overrideMimeType("application/pdf; charset=UniJIS-UCS2-H");
xhr.send(null);
return xhr.responseText;
}
function base64encode(binary) {
return btoa(unescape(encodeURIComponent(binary)));
}
var binary = getBinary('http://localhost/first.pdf');
var base64encoded = base64encode(binary);
data = "data:application/pdf;base64,"+base64encoded;
the data is contain only a plain pdf. how can i resolve it ?

JavaScript - how to view raw data for an image

Is it possible to view the raw data for an image file in javascript?
I'm trying to write a script that converts an image into its hex dump.
How can I view the data I'm writing to the image file?
You can do this with XHR:
var xhr = new XMLHttpRequest();
xhr.open('GET', '/my/image/file.png', true);
xhr.responseType = 'arraybuffer'; // this will accept the response as an ArrayBuffer
xhr.onload = function(buffer) {
var words = new Uint32Array(buffer),
hex = '';
for (var i = 0; i < words.length; i++) {
hex += words.get(i).toString(16); // this will convert it to a 4byte hex string
}
console.log(hex);
};
xhr.send();
Look at the doc for ArrayBuffers and TypedArrays
And you can see how I use it in testing here
Is it possible to get the source code of a file in javascript?
Find the URL for the script and load that into your browser. (Or use Firebug)

Categories