当前位置: 首页 > 后端技术 > Node.js

eggjs文件下载服务

时间:2023-04-03 19:01:05 Node.js

后台方法代码asyncdownload(){const{ctx,app}=this;letfileName='hello.js'constfilePath=path.resolve(app.config.static.dir,fileName);//ctx.attachment([filename],[options])将Content-Disposition设置为“attachment”以指示客户端提示下载。ctx.attachment(fileName,{fallback:true,type:'attachment'//[string]attachment/inline});constfileSize=fs.statSync(filePath).size;ctx.set('Content-Length',fileSize)ctx.set('Content-Disposition',`attachment;filename=${fileName}`)ctx.body=fs.createReadStream(filePath);}前端代码使用Blob和ajax什么是Blob:Blob存储了大量的二进制Data,Blob本身有两个属性,即:size和type;我们可以使用blob对象来存储后台返回的文件流。constxhr=newXMLHttpRequest();consturl="http://localhost:7001/download";xhr.open('GET',url,true);//进行中xhr.onprogress=function(ev){//console.log(ev)}//加载中xhr.onload=function(ev){if(xhr.readyState===4&&xhr.status===200){consttype=xhr.getAllResponseHeaders('content-type')varblob=newBlob([xhr.response],{type});varnewUrl=URL.createObjectURL(blob);vara=document.createElement('a');a.href=newUrl;a.download='a.js';//这里的文件名可以从请求下载文件的地方获取a.click()}}xhr.send()这样一个简单的文件下载服务就完成了