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


大文件分片上传

方式一

 方式二 

 

posted @   JackieDYH  阅读(72)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示