egg.js 上传、下载 到第三方服务器

上传

单文件上传

  1. config.default.ts 文件中 增加 multipart
  config.multipart = {
    mode: 'file',
    // allowArrayField: true,
    // ignore: 'match'
  };
  1. controller 层 用files接受

  public async uploadTtFile() {

    // file.fieldname:文件字段名称
    // file.filename:文件的原始文件名
    // file.encoding:文件编码
    // file.mime:文件 MIME 类型
    // file.fields:文件字段的其他属性
    // file.filepath:文件的临时路径

    const { ctx } = this;
    const params = ctx.request.files[0]; // files 接收
    try {
      const response = await ctx.service.troubleTicket.uploadTtFile(params);
      const res = ctx.helper.getBaseResponse(response, '', '', ''); // 自定义响应数据处理函数
      const finallyResult = JSON.parse(JSON.stringify(res));
      ctx.body = finallyResult;
    } finally {
      await ctx.cleanupRequestFiles();
    }
  }
  1. service 层 下载一个 formstream( node没有 formData数据格式)
// 1  引入formstream
const FormStream = require('formstream');
  public async uploadTtFile(params) {
  // 获取之前的 header
    const oldHeader = this.config.httpclient.request ? this.config.httpclient.request.headers : {};

    const form = new FormStream();
    form.file('sourceFile', params.filepath);
    let headers = form.headers()
    // 生成符合 multipart/form-data 要求的请求 headers
    const newHeader = {
      ...oldHeader,
      ...headers
    };
    const url = this.config.sourceUrl + 'tt/order/uploadTtFile';
    const response = await this.ctx.curl(url, {
      method: 'POST',
      headers: newHeader,
      // 以 stream 模式提交
      stream: form,

    });
    return response;
  }

下载

后端

直接在 controller 调用第三方了

  1. controller 层
  public async downloadTtFile() {

    const { ctx } = this;
    const params = ctx.request.query;
    const oldHeader = this.config.httpclient.request ? this.config.httpclient.request.headers : {};
    const newHeader = {
      ...oldHeader,
      'Content-Type': 'application/octet-stream', // 修改Content-Type
    };
    const url = this.config.sourceUrl + `tt/order/downloadTtFile`;
    const response = await this.ctx.curl(url, {
      method: 'GET',
      headers: newHeader,
      dataType: '', // egg 默认是 buffer格式
      data: params,
    });
    const res = ctx.helper.getBaseResponse(response);
    ctx.body = res

  }

前端

axios 不用设置 responseType = “blob”;
直接将后端的 buffer 转为前端用的数据格式

    // 下载文件
    downloadTtFile(row) {
      let params = { };
      XXXXXXX.downloadTtFile(params)
        .then((res) => {
          if (res) {
            // 将后端字节转换为前端字节  在转blob
            const arrayBuffer = new Uint8Array( res.data.data).buffer;
            const blob = new Blob([arrayBuffer]);
            const link = document.createElement("a");
            const body = document.querySelector("body");
            link.href = window.URL.createObjectURL(blob); // 创建对象url
            link.setAttribute(
              "download",`${文件名字}${new Date().getTime()}.${文件后缀名}`
            );
            link.style.display = "none";
            body.appendChild(link);
            link.click();
            body.removeChild(link);
            window.URL.revokeObjectURL(link.href); // 通过调用 URL.createObjectURL() 创建的 URL 对象
          }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值