JS FileSaver non interactive - javascript

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');
});
}

Related

load multi json data

var address = [ "data/somedata1.json", "data/somedata2.json", "data/somedata3.json", "data/somedata4.json", "data/somedata5.json"];
and function to import this file
function readData()
{
var loadFile = function (filePath, done)
{
var xhr = new XMLHttpRequest();
xhr.open("GET", filePath, true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.onload = function () { return done(this.responseText) }
xhr.send();
}
address.forEach(function (file, i)
{
loadFile(file, function (responseText)
{
jsonData[i] = JSON.parse(responseText);
if(i === 4)
{
fill(jsonData);
document.getElementById("el").innerHTML = jsonData[2].title3;
Dosometing(jsonData[0])
}
})
})
}
All JSON files have absolute 150kb. Problem is, sometimes when I run this code on website I get jsonData[0] undefinded and sometimes all load success. It means all data are not load properly. What im doing wrong ? There is any chance to write this code better to make sure all files are loaded properly ?
One issue is that even for small files it is not guaranteed, that the downloads finish in order.
It would be better to keep track of the finished download count with a separate variable:
function readData() {
var loadFile = function(filePath, done) {
var xhr = new XMLHttpRequest();
xhr.open("GET", filePath, true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.onload = function() { return done(this.responseText) }
xhr.send();
}
var finishedCount = 0;
address.forEach(function(file, i) {
loadFile(file, function(responseText) {
jsonData[i] = JSON.parse(responseText);
finishedCount++;
if(finishedCount === address.length) {
fill(jsonData[4]);
document.getElementById("el").innerHTML = jsonData[2].title3;
Dosometing(jsonData[0])
}
});
})
}

download multiple images from the server with XMLHttpRequest using javascript

I am using the XMLHttpRequest method to get the url of a single image from the server to download, save and then retrieve it from android local storage, and I have succeeded to get it working for a single image url; NOW I AM STUCK on figuring a way to download multiple images from the server using the same method. Can anyone show spare me a way or two ?
Thanks in advance!!!
here the code which I am using to download a single image
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = "blob";
console.log(xhr);
xhr.onload = function (e) {
console.log(e);
if (xhr.readyState == 4) {
console.log(xhr.response);
// if (success) success(xhr.response);
saveFile(xhr.response, 'images');
}
};
xhr.send();
Assuming you have list of urls from which images can be downloaded, you can use a simple for loop and store XMLHttpRequest variable in an array.
var xhrList = [];
var urlList = ['example.com/image1',
'example.com/image2',
'example.com/image2'];
for (var i=0; i< urlList.length; i++){
xhrList[i] = new XMLHttpRequest();
xhrList[i].open('GET', urlList[i], true);
xhrList[i].responseType = "blob";
console.log(xhrList[i]);
xhrList[i].onload = function (e) {
console.log(e);
if (this.readyState == 4) {
console.log(this.response);
// if (success) success(this.response);
saveFile(this.response, 'images');
}
};
xhrList[i].send();
}

How do I convert a png to a base64 string using javascript?

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

using zip.js to read a zip file via xmlhttp/ajax call on Node.js

I am trying to :
Send a zip file via xmlhttp to the client
then read the file using zip.js and render its contents
I successfully receive the binary of the file i.e. the success callback is called but I get and error when I try to do getEntries. I think the error is with the way of sending stream , please help.
Error msg :
Error in reading zip file
My client side code (using angular) :
$http.get(window.location.origin + '/book/'+bookName,{responseType:"Blob"}).
success(function (data , error) {
var a = new Uint8Array(data);
//var dataView = new DataView(data);
//var blob = new Blob(dataView.buffer);
zip.useWebWorkers = true;
zip.workerScriptsPath = '/js/app/';
zip.createReader(new zip.BlobReader(data), function(reader) {
// get all entries from the zip
reader.getEntries(function(entries) { //HERE I GET THE ERROR
if (entries.length) {
// get first entry content as text
entries[0].getData(new zip.TextWriter(), function(text) {
// text contains the entry data as a String
console.log(text);
// close the zip reader
reader.close(function() {
// onclose callback
var a = 0;
});
}, function(current, total) {
// onprogress callback
var a = 0;
});
}
});
},
function(error) {
// onerror callback
var a = 0;
});
})
.error( function (data , error) {
var a = 0;
});
My Server side code on Node:
router.get('/book/:bookName',function (req , res ) {
console.log('Inside book reading block : ' + req.params.bookName);
req.params.bookName += '.zip';
var filePath = path.join(__dirname,'/../\\public\\books\\' ,req.params.bookName );
var stat = fileSystem.statSync(filePath);
res.writeHead(200, {
//'Content-Type': 'application/zip',
'Content-Type': 'blob',
'Content-Length': stat.size
});
var readStream = fileSystem.createReadStream(filePath);
// replace all the event handlers with a simple call to readStream.pipe()
readStream.pipe(res);
});
It is probable that you might have already found a solution. I faced the same problem today and this is how I solved it in plain javascript:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'assets/object/sample.zip', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
// response is unsigned 8 bit integer
var responseArray = new Uint8Array(this.response);
var blobData = new Blob([responseArray], {
type: 'application/zip'
});
zip.createReader(new zip.BlobReader(blobData), function(zipReader) {
zipReader.getEntries(displayEntries);
}, onerror);
};
xhr.send();
The problem I see in your code is that you are changing the value to Uint8Array and assigning it to var a, but still use the raw data in blobreader. Also the blob reader required blob and not an array. So you should have converted var a into blob and then used it for reading.

How to download files using javascript asynchronously?

I'm building a Chrome extension to download a series of files from a site. The downloading function is derived from How to save a file from a URL with JavaScript.
The program structure is like:
function download()
{
while(there are still files to download)
{
saveFile(url);
}
}
But I find that all the files are actually written to disk at once after download() returns. And the addresses of those files start with blob: when examine from Chrome's downloads manager.
I wonder if I make the call to saveFile asynchronously, those files could be written one at a time.
Using promises, which are available in Chrome out of the box, you can define the functions like so:
// Download a file form a url.
function saveFile(url) {
return new Promise(function(resolve, reject) {
// Get file name from url.
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
resolve(xhr);
};
xhr.onerror = reject;
xhr.open('GET', url);
xhr.send();
}).then(function(xhr) {
var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
var a = document.createElement('a');
a.href = window.URL.createObjectURL(xhr.response); // xhr.response is a blob
a.download = filename; // Set the file name.
a.style.display = 'none';
document.body.appendChild(a);
a.click();
return xhr;
});
}
function download(urls) {
return Promise.all(urls.map(saveFile));
}
Using it:
download.then(function() {
alert("all files downloaded");
}).catch(function(e) {
alert("something went wrong: " + e);
});
If you want to wait for 1 file to download before proceeding with next, the download function should be written like:
function download(urls) {
var cur = Promise.resolve();
urls.forEach(function(url) {
cur = cur.then(function() {
return saveFile(url);
});
});
return cur;
}
Usage is same as before.

Categories