其他分享
首页 > 其他分享> > 一文搞懂eggjs中上传文件

一文搞懂eggjs中上传文件

作者:互联网

一、基本的配置

eggjs中上传文件的官方文档

二、使用form表单上传

async create() {
  // 获取文件流
  const stream = await this.ctx.getFileStream();
  // 定义文件名
  const filename = Date.now() + path.extname(stream.filename).toLocaleLowerCase();
  // 目标文件
  const target = path.join('app/public/uploads', filename);
  //
  const writeStream = fs.createWriteStream(target);
  console.log('-----------获取表单中其它数据 start--------------');
  console.log(stream.fields);
  console.log('-----------获取表单中其它数据 end--------------');
  try {
    //异步把文件流 写入
    await awaitWriteStream(stream.pipe(writeStream));
  } catch (err) {
    //如果出现错误,关闭管道
    await sendToWormhole(stream);
    // 自定义方法
    this.error(err);
  }
  // 自定义方法
  this.success({ url: '/public/uploads/' + filename });
}

三、使用ajax上传文件

四、对上传的文件根据时间分类归档

五、提取到基类的控制器中并且进行传递参数分类

标签:const,stream,await,filename,eggjs,path,搞懂,dirname,上传
来源: https://blog.51cto.com/u_3409716/2904732