Reputation: 95
I am currently writing a chrome extension and am stuck at how to handle xmlhttprequest's responsetext as a file. As the title said, I need to download the mp3 given a link and save it as a real physical file anywhere that I can access again in my extension. I can't seem to find information on how to save a file from javascript given the type is not simple text. Any help is appreciated, thanks.
Upvotes: 0
Views: 3788
Reputation: 16706
thi is the function that loads and mp3 in your case using xhr , covertsit to base64 an then executes a function with the base64 file string
var xhrfile=function(i,f){
var c=new XMLHttpRequest();
c.open('GET',i);
c.responseType='arraybuffer';
//c.onprogress=function(e){var perc=Math.round((e.loaded/e.total)*100)+' of 100'};
c.onload=function(e){
var u8=new Uint8Array(this.response),ic=u8.length,bs=[];
while(ic--){bs[ic]=String.fromCharCode(u8[ic]);};
f('data:audio/mpeg;base64,'+btoa(bs.join('')));
};
c.send();
}
usage:
xhrfile('http://domain.com/your.mp3',filefunc)
now as you want to save the file use indexedDB,websql,localstorage,fileApi or whatever you want.... it's a string now.
consider that this mentioned saving possibilities have filesize limitations.
you can also simply output the file to download:
var filefunc=function(mp3data){
var a=document.createElement('a');
a.download='mp3name.mp3';
a.href=mp3data;
a.innerText='download the file';
document.body.appendChild(a);
}
i don't tested this function with mp3... i know that it works on images and other small files.maybe start with a small mp3 file.
here is the blob version.
var xhrfile=function(i,f){
var c=new XMLHttpRequest();
c.open('GET',i);
c.responseType='arraybuffer';
c.onload=function(e){
var blob = new Blob([this.response]);
f(blob);
};
c.send();
}
blob to object url:
var objurl=window.URL.createObjectURL(blob);
free memory
window.URL.revokeObjectURL(objurl);
Upvotes: 1