[英]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. 我目前正在编写一个chrome扩展名,并停留在如何将xmlhttprequest的responsetext作为文件处理的问题上。 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. 如标题所述,我需要下载给定链接的mp3,并将其另存为可以在扩展程序中再次访问的任何实际物理文件。 I can't seem to find information on how to save a file from javascript given the type is not simple text. 鉴于类型不是简单的文本,我似乎无法找到有关如何从javascript保存文件的信息。 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 thi是您使用xhr加载和mp3的函数,Covertsit到base64然后使用base64文件字符串执行一个函数
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. 现在,要保存文件,请使用indexedDB,websql,localstorage,fileApi或任何您想要的文件。...现在是一个字符串。
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. 我没有用mp3测试此功能...我知道它可以在图像和其他小文件上工作。也许从一个小mp3文件开始。
here is the blob version. 这是Blob版本。
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: Blob到对象网址:
var objurl=window.URL.createObjectURL(blob);
free memory 可用内存
window.URL.revokeObjectURL(objurl);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.