简体   繁体   中英

download mp3 file through xmlhttprequest and save it as a file somewhere for upload later

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM