eggjs文件下载服务-功能
后台方法
async download() {
const {ctx,app} =this;
let fileName = 'hello.js'
const filePath = path.resolve(app.config.static.dir,fileName);
// ctx.attachment([filename], [options]) 将 Content-Disposition 设置为 “附件” 以指示客户端提示下载。
ctx.attachment(fileName,{
fallback:true,
type:'attachment' // [string] attachment/inline
});
const fileSize = 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 存储大量的二进制数据,Blob自己本身的属性有两个,分别是:size 和 type;我们可以使用blob对象存储后台返回的文件流
const xhr = new XMLHttpRequest();
const url ="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){
const type = xhr.getAllResponseHeaders('content-type')
var blob = new Blob([xhr.response],{type});
var newUrl = URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = newUrl;
a.download = 'a.js'; // 这里的文件名可以在请求下载文件哪里获取
a.click()
}
}
xhr.send()

大文件分片上传

方式一

方式二

本文来自博客园,作者:JackieDYH,转载请注明原文链接:https://www.cnblogs.com/JackieDYH/p/17634127.html

浙公网安备 33010602011771号