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.
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 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?
I have an array of file to save by using a loop and i generate the name of each file. I want to save file directly (in non interactive way) without asking me to confirm. How can i do ?
Here is my code for saving file
var url = img.src.replace(/^data:image\/[^;]/, 'data:application/octet-stream');
var xhr = new XMLHttpRequest();
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) {
var filesaver = require('file-saver');
filesaver.saveAs(xhr.response, nameFile); // nameFile the name of file to be saved
}
};
xhr.send(); //Request is sent
Finally, i find a solution, instead of saving file, i write it by creating a new one.
for (var i = 0; i < tabForm.length; i++) {
var imgData = $('#affichageqr')[0].childNodes[1].childNodes[0].src;
var data = imgData.replace(/^data:image\/\w+;base64,/, '');
fs.writeFile(qrcode.getNomQRCode()+'.jpeg', data, {encoding: 'base64'}, function(err){
if (err) {
console.log('err', err);
}
console.log('success');
});
}
I want to get a Base64 encoded file from the server in order to use it in a dataURL so I use:
xhr.overrideMimeType("text/plain; charset=x-user-defined");
So I get the unprocessed data to perform the base64 encoding on.
But I also want to get the mimetype originally returned from the server to declare my dataURL:
var dataUrl = 'data:'+mimetype+';base64,'+b64;
when I try something like the following:
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
var mimetype = xhr.getResponseHeader('content-type');
xhr.overrideMimeType("text/plain; charset=x-user-defined");
xhr.send(null);
the content-type returned is always null
Full source:
function getFileDataUrl(link,mimetype)
{
var url = location.origin+link;
var getBinary = function (url)
{
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
if(mimetype == null)
{
mimetype = xhr.getResponseHeader('content-type');
console.log('mimetype='+mimetype);
}
xhr.overrideMimeType("text/plain; charset=x-user-defined");
xhr.send(null);
return xhr.responseText;
};
var bin = getBinary(url);
var b64 = base64Encode(bin);
var dataUrl = 'data:'+mimetype+';base64,'+b64;
return dataUrl;
}
var dataUrl = getFileDataUrl(link,null);
You can set responseType of XMLHttpRequest to "blob" or "arraybuffer" then use FileReader, FileReader.prototype.readAsDataURL() on response. Though note, onload event of FileReader returns results asynchronously. To read file synchronously you can use Worker and FileReaderSync()
var reader = new FileReader();
reader.onload = function() {
// do stuff with `reader.result`
console.log(reader.result);
}
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function() {
reader.readAsDataURL(xhr.response);
}
xhr.send(null);
At chromium synchronous XMLHttpRequest() is deprecated, see https://xhr.spec.whatwg.org/.
You can use Promise at main thread to get data URI of requested resource using either Worker or when FileReader load event is dispatched. Or use synchronous XMLHttpRequest() and FileReaderSync() at Worker thread, then listen for message event at main thread, use .then() to get Promise value.
Main thread
var worker = new Worker("worker.js");
var url = "path/to/resource";
function getFileDataUrl(url) {
return new Promise(function(resolve, reject) {
worker.addEventListener("message", function(e) {
resolve(e.data)
});
worker.postMessage(url);
})
}
getFileDataUrl(url)
.then(function(data) {
console.log(data)
}, function(err) {
console.log(err)
});
worker.js
var reader = new FileReaderSync();
var request = new XMLHttpRequest();
self.addEventListener("message", function(e) {
var reader = new FileReaderSync();
request.open("GET", e.data, false);
request.responseType = "blob";
request.send(null);
self.postMessage(reader.readAsDataURL(request.response));
});
plnkr http://plnkr.co/edit/gayWpkTVydmKYMnPr3jD?p=preview
I'm trying to use filepicker.io to fetch binary data and pass it into a function like this:
var doSomething = function(arrayBuffer) {
var u16 = new Int16Array(arrayBuffer);
}
I have no idea how to convert the binary into arraybuffer like this:
filepicker.getContents(url, function(data){
//convert data into arraybuffer
}
I tried to follow this tutorial on XMLHttpRequest but does't not work.
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
doSomething(this.response);
};
You are not calling .send with your XHR
xhr.send(null);