I have local image URL and I want to get the blob from it.
The only way I found was to do HTTP request 'get' on the local URL, and read the returned blob... but this is such a strange way.
The code snippet using HTTP:
function readBody(xhr) {
var data;
if (!xhr.responseType || xhr.responseType === "text") {
data = xhr.responseText;
} else if (xhr.responseType === "document") {
data = xhr.responseXML;
} else {
data = xhr.response;
}
return data;
}
var xhr=new XMLHttpRequest();
xhr.open('GET',results[i],true);
xhr.responseType='blob';
xhr.send();
xhr.onreadystatechange=function()
{
var blob;
if(xhr.readyState==4)
{
blob=readBody(xhr);
uploadPhoto(blob,storageRef);
}
};
Your image needs to be converted to base64 and then from base64 in to binary. This is done using .toDataURL() and dataURItoBlob()
It's pretty fiddly process, I've created a tutorial you can follow which walks you through the process.
Related
Can you please tell me how can I correctly store some js file to localstorage and then run it.
So I have found some code that stores an image, but can I store a js file?
Here is the code:
https://gist.github.com/robnyman/1875344
// Getting a file through XMLHttpRequest as an arraybuffer and creating a Blob
var rhinoStorage = localStorage.getItem("rhino"),
rhino = document.getElementById("rhino");
if (rhinoStorage) {
// Reuse existing Data URL from localStorage
rhino.setAttribute("src", rhinoStorage);
}
else {
// Create XHR and FileReader objects
var xhr = new XMLHttpRequest(),
fileReader = new FileReader();
xhr.open("GET", "rhino.png", true);
// Set the responseType to blob
xhr.responseType = "blob";
xhr.addEventListener("load", function () {
if (xhr.status === 200) {
// onload needed since Google Chrome doesn't support addEventListener for FileReader
fileReader.onload = function (evt) {
// Read out file contents as a Data URL
var result = evt.target.result;
// Set image src to Data URL
rhino.setAttribute("src", result);
// Store Data URL in localStorage
try {
localStorage.setItem("rhino", result);
}
catch (e) {
console.log("Storage failed: " + e);
}
};
// Load blob as Data URL
fileReader.readAsDataURL(xhr.response);
}
}, false);
// Send XHR
xhr.send();
}
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');
});
}
How would I display data from this json file when the extension is not .json? The other related questions i've found have involved files with .json as an extension and as a bit of a beginner to this I am struggling with it.
https://fantasy.premierleague.com/drf/elements/
Thanks.
Just treat it as if it was a JSON file except that there wont be a .json extension to your URL. So in pure JavaScript you can do this:
var request = new XMLHttpRequest();
var url = 'https://fantasy.premierleague.com/drf/elements/';
var jsonResponse;
httpRequest.onreadystatechange = parseJSON;
request.open('GET', url);
request.send();
function parseJSON() {
if (request.readyState() === XMLHttpRequest.done) {
if (request.status == 200) {
jsonResponse = JSON.parse(request.responseText);
} else {
console.log('An error occurred while processing the request.');
}
}
}
I've tried several different options, so many I've lost track of them all. I'm making an AJAX request and the response is of Content-Type: image/png, and the contents are the actual image.
I would absolutely love to display the image, but nothing seems to work the way I want:
// imgdata contains a string that looks like this: "�PNG..."
var img = document.createElement('img');
// no good
img.src = 'data:image/png;base64,' + btoa(unescape(encodeURIComponent(data)));
// also no good
img.src = 'data:image/png;base64,' + btoa(encodeURIComponent(data));
// also no good
img.src = 'data:image/png;base64,' + btoa($.map(d, function(x){ return x.charCodeAt(0); }))
I've tried a few other things, but still no dice.
Is there any simple (or even complciated) way to do this in Javascript?
This isn't done with base64 but with blob, but you'll get exactly the same result:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
var img = document.getElementById('image');
var url = window.URL || window.webkitURL;
img.src = url.createObjectURL(this.response);
}
}
// Relative path because :
// No 'Access-Control-Allow-Origin' header is present...
xhr.open('GET', '/img/logo.png');
xhr.responseType = 'blob';
xhr.send();
Demo here : http://jsfiddle.net/sparkup/sp4cukee/
If you're serving this file via node.js or PHP you could always write the file to disk in temporary location server-side, serve it, and then immediately delete it afterwards.
var tempFile = 'path/to/file.jpg';
// Write the file to disk
fs.writeFile(tempFile, base64versionOfPhoto, function (err) {
if (err) {
res.header("Content-Type","application/json");
return res.send(JSON.stringify(err));
} else {
// Pipe the jpg to the user
res.header("Content-Type","image/jpeg");
var readStream = fs.createReadStream(tempFile);
readStream.pipe(res, {end: false});
readStream.on("end", function () {
res.end();
// Delete the file
fs.unlink(tempFile, function (err) {
if (err) console.log(err);
});
});
}
});
I'm creating a asynchronous upload element with the javascript code bellow:
$("#file-input").change(function(){
uploadImage(this.files[0]);
});
function uploadImage(imageFileHTMLInput) {
var xml = new XMLHttpRequest();
var data = new FormData();
data.append('file', cover);
xml.open('POST', url);
xml.send(data);
xml.onreadystatechange = function() {
if(xml.readyState === 4) {
if(xml.status === 200) {
var response = JSON.parse(xml.responseText);
// handle response
} else {
var error = JSON.parse(xml.responseText);
// handle error
}
}
};
}
How can I handle this post in a Symfony2 server? I need to save this file in the server and return the image url.
UPDATED:
I made some changes on my code to works fine. I have change all way to do the upload.
You will get the data from your POST request in the controller via
$request->files->get('your_file_identifier_name');
Server side, you'll get an instance of File