I am trying to input a file and get the same output as php's file_get_contents() but doing so in javascript. My javascript code is below:
var xhr = new XMLHttpRequest();
xhr.open( "GET", "http://localhost:3000/line.png", true );
xhr.responseType = "arraybuffer";
xhr.onload = function( e ) {
var arrayBufferView = new Uint8Array( this.response );
console.log(arrayBufferView);
var blob = new Blob( [ arrayBufferView ], { type: "image/png" } );
var reader = new FileReader();
reader.onloadend = function () {
var blobStr = reader.result;
console.log(blobStr);
}
reader.readAsText(blob, "iso-8859-1");
};
xhr.send();
When I use the above code I get what appears to be the exact same output as php's file_get_contents(). However it ends up being different output because when I md5 each string, I get different results. My example image is below:
Looking at the javascript string outputted in a div, I see this:
Looking at the php string outputted in a div, I see this:
As you can see, both look the same, except for maybe some formatting differences? Would this be the cause of my issues? How would I force the javascript version to have the same output as the php version?
Related
I am trying to achieve to create a File object from a URL. I tried hard but didn't find a solution to resolve this issue. Could someone please help me how to resolve this issue?
code
let blobImages =
nextProps &&
nextProps.input &&
nextProps.input.value &&
nextProps.input.value.map((item) => {
let file = new File([item.url], { type: 'image/png' })
return file
})
I am using this code but this code doesn't work it give me break image result.
Try the following approach:
HTML:
<img id="myImage"/>
JAVASCRIPT:
// Accept an external ArrayBuffer from a service (cloud,external server etc.)
var request = new XMLHttpRequest();
// For testing lets say this is your URL
request.open( "GET", "https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/Circle-icons-computer.svg/512px-Circle-icons-computer.svg.png", true );
// Identify that your response has declared as arraybuffer
request.responseType = "arraybuffer";
// If you are using DOM object, definitelly you will use blob to create your file object
request.onload = function( e ) {
var arrayBufferView = new Uint8Array( this.response );
var blob = new Blob( [ arrayBufferView ], { type: "image/jpeg" } );
// Parse and create your image from url
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL( blob );
// Access your div element, where your photo will be presented.
// Here instead you can alter the code to download the image as file...
var img = document.querySelector( "#myImage" );
img.src = imageUrl;
};
request.send();
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
});
I get from the server an object that should represent a file, and it looks like this:
name: "סריקה0252.pdf",
url: "https:XYZ/ABC/1/סריקה0252_28-05-2019_11:24:40.pdf"
Now, I want to convert it to a file of JavaScript ,
Is it possible to do so?
function urlToBlob(url){
return new Promise((resolve,reject)=>{
var xhr = new XMLHttpRequest();
xhr.open( "GET", url, true );
xhr.responseType = "blob";
xhr.onload = function( e ) {
resolve(this.response)
};
xhr.onerror = function( error ){
reject(error)
}
xhr.send();
})
}
let fileUrl = "https:XYZ/ABC/1/סריקה0252_28-05-2019_11:24:40.pdf"
urlToBlob(fileUrl).then(function(blob){
console.log(blob)
// you will get blob object of that file here
})
Here is the function to convert it. this will load the file first to the local. once it will be loaded, it will return blob object as return type is defined as a blob.
I have tried various versions now, but I simply seem to miss something.
Funnily I haven't found an example for this so far.
Only thing seems to be uploaded by my Javascript is [object XMLDocument].
(I try to save the XML-Document in the receiving perl-script, and that's the string that the perl script writes to the outputfile.)
For the JavaScript part I looked at Mozilla's Using FormData Objects.
And then came up with:
function httpPerlUploadBigData(fuPerlTarget, contentToWrite, fuCallMeOnLoad) {
var formData = new FormData();
var blob = new Blob([contentToWrite], { type: "text/xml"});
formData.append('file', blob, "filename.txt");
formData.append('bigcontent', contentToWrite);
formData.append('saveOnServerAs', 'temp.xml');
var MyThis = this;
this.perlTarget = fuPerlTarget;
this.callMeOnLoad = fuCallMeOnLoad;
var oReq = new XMLHttpRequest();
oReq.open("POST", MyThis.perlTarget, true);
oReq.onload = function(e) {
MyThis.callMeOnLoad( e.target.response );
};
oReq.send(formData);
}
I send contentToWrite twice because I would like to upload it in a way that the script sees as an uploaded file. The other code I tried before uploaded it as plain text, but because this is XML I guess an upload as sort of file would be better.
contentToWrite seems to contain an XMLDocument object. The Blob constructor accepts an Array of ArrayBuffer, ArrayBufferView, Blob, DOMString objects. So you must serialize the XML document first:
var serializer = new XMLSerializer();
var xmlString = serializer.serializeToString(contentToWrite);
var blob = new Blob([ xmlString ], { type: "text/xml"});
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 ?