Generate Zip file contain list of Files without JSZip library - javascript

Hello Developers,
I'm trying to download the list of files getting form XMLHttpRequest() request method and store it in the array of files. I wanted to zip all the files in an array using javascript without using any 3rd party library.
I have tried to achieve this by URL.createObjectURL(url) and URL.revokeObjectURL(url) method but the file I'm getting is corrupted.
I'm Sharing my code snippet please help me out
const URLS = [
'https://vr.josh.earth/assets/2dimages/saturnv.jpg',
'https://vr.josh.earth/assets/360images/hotel_small.jpg',
'https://vr.josh.earth/assets/360images/redwoods.jpg'
];
$(document).ready(function () {
debugger
$("#downloadAll").click(function () {
var blob = new Array();
var files = new Array();
URLS.forEach(function (url, i) {
getRawData(url, function (err, data) {
debugger
var mydata = data;
// mydata = btoa(encodeURIComponent(data));
// var blobData = b64toBlob(mydata , 'image/jpg');
var blobData = new Blob([mydata], { type: 'image/jpg' });
blob.push(blobData);
var filename = "testFiles" + i + ".jpg";
var file = blobToFile(blobData, filename);
files.push(file);
debugger
if (files.length == URLS.length) {
// saveData(blob, "fileName.zip");
var AllBlobData = new Blob([blob], { type: 'application/zip' });
saveData(AllBlobData, "Test.zip");
// saveFile("DownloadFiles.zip", "application/zip", files)
}
});
});
});
});
//Retriving record using XMLHttpRequest() method.
function getRawData(urlPath, callback, progress) {
var request = new XMLHttpRequest();
request.open("GET", urlPath, true);
request.setRequestHeader('Accept', '');
if ('responseType' in request)
request.responseType = "arraybuffer"
if (request.overrideMimeType)
request.overrideMimeType('text/plain; charset=x-user-defined');
request.send();
var file, err;
request.onreadystatechange = function () {
if (this.readyState === 4) {
request.onreadystatechange = null;
if (this.status === 200) {
try {
debugger
var file = request.response || request.responseText;
} catch (error) {
throw error;
}
callback(err, file);
} else {
debugger
callback(new Error("Ajax Error!!"))
}
} else {
debugger
}
}
}
//For Saving the file into zip
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
// var AllBlobs = new Blob([data], { type: "" });//application/zip //octet/stream
// var url = window.URL.createObjectURL(AllBlobs);
var url = window.URL.createObjectURL(data);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
//Downloaded Zip File
enter image description here

Related

Image Blob - Pop up window not showing content

I am working on displaying an image in blob
const file = new Blob([response.data], { type: 'image/png' });
const fileURL = URL.createObjectURL(file);
window.open(fileURL);
console.log('fileURL', fileURL);
const image = document.createElement('img');
I am getting this response
PNG
IHDR2²OósRGB®ÎégAMA±üa pHYsÃÃÇo¨dã¼IDATx^ìý=ô<Ó¶Þ;Ðزg
cõ-EVÙÚÜòfã·#cV0¡\¡5È·Eüü$
]EGâ¹AD" èî÷½þûeü÷_ý×ð\¸³µ°ñ F\¸³µ°ñ F\¸³µ°ñ F\¸³µ°ñ FáË¥ßçòüù«&Þv~ÑTU?ÿ^Ý}öòóÜï×'sµùÔ¤|¼þåúE8ñp
ÎÛ3Î0
¹Þuv]áÌäZ×G#¬Ïv\f.ý{ý>ã¦ñï÷õÈõÁÛÅØã·n6«ÿÞpÙ.2ßƹod
ÕEk+bv|_Hß5yÏçnØ1C´ìOÑÞøVÛ|¯
¤=ûsÔ_}BKíWÊó÷¿ç¯×ò_Þòu¸ÈÜ\dF¾a
¯FXí¸.Í\"øãñXÈ|8°àmÇýØa)#
F;L æ Øñæá_ðɾ´o»ìÔq­#ºMxVÍ_±S.|íËs¿4×â7÷="/2GýÝù¹uyZ{c6Â×·°ãÛÆyqÎ_\ÁFøÎ)¼>a}¶àº¸r)Ý
ÄÛ® ÖáÌÁÁ\à"ó'â7|ú®HNë'/Õû
D ¶³c.!lÿȶËhê¾ü"sÆß4ò#^¦¬XxcvÒ׷̽ÀEf$.í7a}¶àº4s)úáñtøÖEÛ´´ve¬í`Ê"UWäÃÛèÁ¿X}½2få¯âH²×n£Îy)U|Íg­]O½{þ«}Ï®¹JÈ-ýðkÙʯóR¸/ZLBd[NN±¨ùÖÌ¥x}³è­:#"9¯yoL÷ÿBÎj¸Õvöú_æ´v8çï.òú©Cµ-/óÊõÑ _{¹³æb[.êòRÙÖ£'lµo¦¬aò/ÌÕ1>ÿ¶ª<hPù½nüä7Ûzéú]Ïúg­ó=ó´ÞÛúºÓ¾KéåSÀÅ [¥8ìµÛ¸üí®õFxOáõÑë³×¥KËG1ýÿF&Êw\c´Û6¶Éðqò&¹mYÐÜ#ÝÄØtÓYÇÈ>Ó'´«6"áW±5k>\¥ñ[ëñîùkö[1X}Íãq{1K_1o­­Óç÷1ãÕ8t*Þå+V±]/G´v5ZI¨Úɹ¼Æ5­
µç°½Ö¿cþîÄÊLò#¬1CƳ¾zrgô·mbÄjïøÛX9N½oû½â²ÖhÏZßlë]ßo=Ku³MâáôÙ;V¼W·õN}¹­¾ýíÛH¨>4ðÆ`>çyÐ9x¾¿¢_;GC[
¯FXí¸.¾\J;Ýu¼í2ñÃccçp^iL|CJ~\vv­obú<ª
Ê··á¾Þ9k¸ðÞùöwÆ ö£ôUcgû"þÏZ5Ú7xoìq*ò¡Zå#UÛySÞkc+{gsÛw¥Me;û²ÆS×_Ò&wzßwÉýçSoçÙÂ_#2Vïÿ¶3F¬FÏoýVì÷{¾YûÇï4WÍnÀ²]û·wãÖ;ÙëÅÂ>¯´g6®qÕüìåD·ñøëYë°®^°>Ûp]þ4´õáUíøH}{cø63}ccªXòâÙØ%yCZÛx6±óÉã/ýºkyïü
ûyncÖTYü¯b`Ì)|ÜrY÷9ÁÛªßA7úÖGSÿ]sßrSôÉöëÒË
¥Ms.Ù'ÕfÏ_ï¼
´<`Äï-¯­+f#|ÈÜÑsqä·1bõÖñßddÐ7k¿óø½å¨Gíêùéy7·wܾ5¦k\#.¢ÂSx}4ÂúlÀuùÓ\ÒHãÀí\Yîæªí£§ÞÄV±AiÞóñHÜÏgyBØR:ñîù«ö¶¦r®úF޳ث¦®=+°\Ö}Î0_µ4y§o
ÝXi(ßv}ïGDrkåËË%_íò}æÿnÙ<ìoÖväÉ _ÿâÛV1â°g|1\Ìñ{ë³cmZ߬ùÎí·½ß[¶Óóìßéy_onÏe!å%ïçÏq׸Æ<´ý¾÷týu¯õFxNáõÑë³×åOsI; ["ÅhçÛÈä¸qDüL´¡o¸cçCIïÚ¶ß;Ã~sMùsßÅÿ*¿9½»#Ç;°voõâFãÛ®|<(ùÁî³ãð=Úa±mÎå'Ù¬:HùÛAËN«×C¾úrgì·ÝÀùñ;hùNi¼ßóÍÚïöûlm},ÛÕóÓóðÆ[>çö|öKnÒ²/¿]ãqù
ìPx}4ÂúlÀuùÓ\j~àv»6²î :Ã61µ
ÛÄbÞ&;v>5}ÛoxrfMc1cvµ9;õặbZÞ/ëú: ßìÛ7VªøUúÉyNtN;iîÖþbÌÍ°|ÿÿÕ
®õ·V¯G|uæÎÐo»Sãwáv8¶Ý=߬ýîßud¯}n³úwvÇ×ÛsÙ¹pîÛs«~,&ïÄ寽\ëñúhõÙëò§¹¤Æ#Ñ ßF¹7ź{h×ßàmb_IðÐ6ä+ï£æì±­yPÞ=ï¦v$ÙðlóÃ7¦Ö. ÆX°q)Ù¾×ñó­àöm/v+ñ=ó5çz[=;+ùÀg1Ù+6,Û$¿Ö
÷·­6^ùêË=e_7ê·Ý¢õ=÷Ç/kXwíÚq~/8µ÷ö3ým½ëúÞÓo9ÇûW­¿bóÜ<¯7·çµ¿æ"+Ô×®qY,qì5æ
ßȺ¸üÝ£¡-×G#¬Ïv\?Í¥øᱬuðròKþè½Yl©´¥Â¸Mlû°ø¨mtÜNSÝùlvøØ÷Îß°ãÂ×´ö=ôIµòÃ1fDɯ}³îsMséÏÓ²Kö_í7È·o¬8Ú·(öóÂß­&õÖïV¬ñ,´q­95l¯¾üþÖmJm-ZyPèæ#fG}uä'¾ítÙ=ãù8óMä·+â+íê~&Zï"¿¹4«mfC]÷Ãó8¾ÞÜÏ~ªó¼I}÷¬igÜ3>Ø?»ßÉwähxOáõÑë³×¹ôÙèóBÞ°Ô|é"£¬-|æùóÅ|Ûú.gk?aâ¹ôáärÕUù3àïÅø©/|W¼È|Ýú&gk?a}¶àº ¾ñ+û¥X¾$|ÆÁ%/2o;Sßào°AáõÑë³×¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¢K?Ïð/á_ÿff¬á=þÑ´4?Ïsÿøz}Ä2ßç?þU{ß7?¾!׿ÏÈð´´ß;Ög;®K+ :¾¯¿Èhÿ¢ñZÈ¿Û±)ßèût9ýÿXc\dt¼>bO
.2À.2`#^°>Ûp]¾*þ½~>!zAþzþÆøóÅÇ¿ß× bó"S?K¾:sg¬ÎýcâÛà|¼)Ny>xóããóè¯÷àSà"6fk?aý«Ä'øh¾*¾úÀ_ÏÿSDlþMKåó"³x.A×ò_
±:÷OooðñVà"3¿ÞOØ­ýõ¯à£iå<TÒFÚÄÒÙÍcÿ(ë~j·|#¬¶Y»ô§¬tĨ5>ßÈ×vÄÊGî·NOÌ?À×p×ZãocXgÇjò¼û"Sæb%m®%gÔxr[æ8+¾G×?0ÂG¯º}oOYñδ+¦[ï"Ü6¿ÐµÁÉïµHÝ1#Û)~Br{,>imø÷×9Ã×qoÝbkWç*¾ÎqÏÚ­ü×÷¹6­ñ×wlîjxæîÍpKB^Px}4ÂúlÀuiåR}øäd]5lÞê&IýÃ&Ê4Mp²
V{7ïÖm|2bWósE´çÖÔK·¿>¾§ó$;ÆÒ0ÆwÛtÄ¢G¯Ñ¶6oÇÔ~Js®|Äÿ3s_·->¦g¥Möëí)ó,´ÞIÛʳ¦
When I reffer some stackoverflow answers I understood my response is wrong. my questions is how to get correct binary response ..
You can use XMLHttpRequest() or fetch() to get response as Blob
let url, w;
let request = fetch("/path/to/image");
request.then(function(response) {
return response.blob() // return `Promise` which resolves to `Blob` of response
})
.then(function(blob) {
url = URL.createObjectURL(blob);
w = window.open(url);
})
.catch(function(err) {
console.log(err)
});
let url, w;
let request = new XMLHttpRequest();
request.open("GET", "/path/to/image");
request.responseType = "blob"; // set `responseType` to `"blob"`
request.onload = function() {
url = URL.createObjectURL(blob);
w = window.open(url);
}
request.onerror = function(e) {
console.log(e);
}
request.send(null);
$http.get(ur1, {
responseType: 'blob'
}).then(function (res) {
this.download(res)
}, function (err) {
conseole.log(err)
})
}
};
this.download = function (data) {
var type = data.headers('Content-Type'),
content = data.data,
fileName = data.headers('x-ms-meta-originalname'),//Get the file name
blob = new Blob([content], {type: type}),
url = window.URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.target="_self";
a.download = fileName;
a.click();
a = undefined;
}
Additinal Details here: http://angularjstricks.blogspot.in/2017/03/download-file-from-server-with-http-in.html

submitting full HTML page to x-www-form-urlencoded as querystring encoding

I am trying to submit full HTML Page to server but I dont have a form to submit. I am not sure if i am doing it correctly but using javascript I am trying to rebuild a json object {html: htmlPage, fileName: "foo" } into a query string and then submit it to server here is the code I have. when i console str the HTML page doesnt look right. I am using jquery
var htmlPage = $("html").html();
var str = { html: htmlPage, fileName: "foo" };
var params = jQuery.param( str );
var xhr = new XMLHttpRequest();
xhr.open('POST', '/', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
if (this.status === 200) {
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
var type = xhr.getResponseHeader('Content-Type');
var blob = new Blob([this.response], { type: type });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
var a = document.createElement("a");
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location = downloadUrl;
}
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
}
}
};
xhr.onerror = function(e) {
console.log('in error', e);
};
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
xhr.send(params);
if you have jQuery, then just use ajax http://api.jquery.com/jquery.ajax/.
This will base64 encode your html, then on the server side you only have to base64 decode it, then use it. And hey the entire html code can't be counted as form-data, it's "text/html".
(updated) Try it, let me know.
// javascript
function _upload(html_string)
{
return $.ajax({
url: '/',
type: 'POST',
headers: {"Content-Type": "application/x-www-form-urlencoded"},
data: {html: btoa(html_string), fileName: "foo" },
success: function(data, textStatus, req){
console.log(textStatus);
},
error: function(req , textStatus, errorThrown){
console.log("jqXHR["+textStatus+"]: "+errorThrown);
console.log('jqXHR.data', req.responseText);
}
});
}

File download from google

I'm working on Google drive integration with salesforce. Currently I'm facing file corruption when I tried to download file using java script. My code is as followed
function downloadGDriveFile() {
var id = '0B3EI0BFOUwSydHZNZXdIZ3lDZzg';
var downloadUrl = 'https://www.googleapis.com/drive/v2/files/'+ id+'?alt=media';
var accessToken = MY ACCESS TOKEN;
var mType = 'image/jpeg';
var name = 'Internet_of_Things.jpg';
if (downloadUrl) {
var xhr = new XMLHttpRequest();
xhr.open('GET', downloadUrl);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.onload = function() {
onDownload(xhr.response);
};
xhr.onerror = function() {
//downloadFile(null);
};
xhr.send();
}
else {
alert("Unable to download file.");
}
}
function onDownload(data) {
var filename = 'Internet_of_Things.jpg';
var blob = new Blob([data], { type: "image/jpeg" });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
// use HTML5 a[download] attribute to specify filename
var a = document.createElement("a");
// safari doesn't support this yet
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
//window.location = downloadUrl;
}
alert(11);
//URL.revokeObjectURL(downloadUrl);
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 1); // cleanup
}
}
when file is downloaded file is corrupted.File content shown as follow
���� JFIF �� hExif MM * > F( 1 N Paint.NET v3.5.11 �� C �� C�� ��" ��
Dose any one can help me to sort this out. Do I need to encode or decode the Response from Google REST API?

webrtc audio record to python

I'm trying to record audio but the files as they are stored on server are only 10kb or less.
The file is being saved to server, and has the correct name, but is 10 kb or less.
In the browser the audio file is capable of being reviewed and plays as expected.
Server side python code:
def save_file(file, filename, path=''):
''' Little helper to save a file
'''
fd = open('%s/%s' % ('/root/ws911/media/', str(path) + str(filename)), 'wb')
#for chunk in file.chunks():
# fd.write(chunk)
fd.write(file)
fd.close()
JavaScript code excerpts:
// PostBlob method uses XHR2 and FormData to submit
// recorded blob to the PHP server
function PostBlob(blob, fileType, fileName) {
// FormData
var formData = new FormData();
formData.append(fileType + '-filename', fileName);
formData.append(fileType + '-blob', blob);
// POST the Blob using XHR2
xhr('xxxxxxxxxxxxxx/get_json/', formData, function(fileURL) {
});
}
var container = document.getElementById('container');
// var legalBufferValues = [256, 512, 1024, 2048, 4096, 8192, 16384];
// sample-rates in at least the range 22050 to 96000.
recordAudio = RecordRTC(stream, {
//bufferSize: 16384,
//sampleRate: 45000,
onAudioProcessStarted: function() {
if (!isFirefox) {
recordVideo.startRecording();
}
}
});
recordAudio.startRecording();
stop.disabled = false;
},
function(error) {
alert(JSON.stringify(error, null, '\t'));
});
};
var fileName;
stop.onclick = function() {
record.disabled = false;
stop.disabled = true;
preview.src = '';
fileName = Math.round(Math.random() * 99999999) + 99999999;
recordAudio.stopRecording(function(url) {
preview.src = url;
PostBlob(recordAudio.getBlob(), 'video', fileName + '.webm');
});
function xhr(url, data, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback(request.responseText);
}
};

How to set the file download location for chrome extension Using JavaScript?

Hi i am downloading selected links using chrome extension but I can't set downloads location. All the urls downloaded to default location of chrome. i know we can't do it because of security reason. can we prompt directory chooser dialog in chrome extension popup from here user can select the Download path.Need any information from my side let me know.
Is this possible at all? Any suggestions on how to go about it?
Thanks in advance
My code
function downloadFile(url, onSuccess,arrayOfUrl,zip) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = "blob";
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (onSuccess)
{
onDownloadComplete(xhr.response, arrayOfUrl,zip)
}
}
}
xhr.send("null");
}
function onDownloadComplete(blobData,urls,zip ){
if (count < urls.length) {
blobToBase64(blobData, function(binaryData){
var fileName = urls[count].substring(urls[count].lastIndexOf('/')+1);
zip.file(fileName+".docx", binaryData, {base64: true});
if (count < urls.length -1){
count++;
downloadFile(urls[count], onDownloadComplete, urls,zip);
}
else {
var content = zip.generate();
var zipName = 'download.zip';
var a = document.createElement('a');
a.href = "data:application/zip;base64," + content;
a.download = zipName;
a.click();
count = 0;
}
});
}
}
popup.js
function onDownloadComplete(blobData,urls,zip ){
if (count < urls.length) {
blobToBase64(blobData, function(binaryData){
// add downloaded file to zip:
var fileName = urls[count].substring(urls[count].lastIndexOf('/')+1);
// zip.file(fileName, binaryData, {base64: true});
zip.file(fileName+".docx", binaryData, {base64: true}); //file"+count+".docx"
if (count < urls.length -1){
count++;
downloadFile(urls[count], onDownloadComplete, urls,zip);
}
else {
chrome.runtime.getBackgroundPage(function () {
zipAndSaveFiles(zip);});
}
});
}
}
**background.js**
function zipAndSaveFiles(zip)
{
var content = zip.generate(zip);
var zipName = 'download.zip';
var dataURL = 'data:application/zip;base64,' + content;
chrome.downloads.download({
url: dataURL,
filename: zipName,
saveAs: true
});
}
Since you are generating and downloading just one ZIP file, you can use the chrome.downloads.download() method. E.g.:
var content = zip.generate();
var zipName = 'download.zip';
var dataURL = 'data:application/zip;base64,' + content;
chrome.downloads.download({
url: dataURL,
filename: zipName,
saveAs: true
});
count = 0;
If you omit the display of a SaveAs dialog, then you can only specify a file name that is inside the user-defined download folder or in a subfolder of it.
Regarding the issue with the popup (see comment below):
You should call the function from your background-page, not the popup. E.g. you could use chrome.runtime.sendMessage/onMessage to pass a message to your background-page:
In background.js:
...
function zipAndSaveFiles(...) { ... }
chrome.runtime.onMessage.addListener(function(msg, sender) {
if ((msg.action === 'zipAndSave')
&& (msg.params !== undefined)) {
zipAndSaveFiles(msg.params);
}
});
In popup.js:
...
chrome.runtime.sendMessage({
action: 'zipAndSave',
params: ['url1', 'url2', 'url3']
});

Categories