egg文件上传

const Controller = require('egg').Controller;
/*const fs = require('mz/fs');*/
const fs = require('fs');
const path = require('path');

module.exports = class extends Controller {
  async upload() {
    const { ctx } = this;
// 获取文件流
    const parts = ctx.multipart();
    let part;
    let result = []
    // parts() 返回 promise 对象
    while ((part = await parts()) != null) {
        let length = 0
        if (part.length) {
            length = part[1]
            // 获取其他参数
        } else {
            if (!part.filename) return
            // 处理文件流
            let file = {}
            let time = Date.now();
            file.name = part.filename
            file.type = part.mimeType
            let filePath = path.join('app/public/uploads', time+part.filename) // 保存地址
            let writable = fs.createWriteStream(filePath)// 创建写入流
            await part.pipe(writable) // 开始写入
            file.path = this.config.serverUrl +'public/uploads/' + time+part.filename
            result.push(file)
        }
    }
    ctx.status = 200
    ctx.body = {
        data: result
    }
  }
};

你可能感兴趣的:(node,egg)