安装插件:
npm i md5 --save
npm i egg-multipart --save
npm i stream-to-array --save
npm i stream-wormhole --save
主要代码: // upload.js
'use strict'; const md5 = require('md5') const path = require("path") const fs = require("fs") const toArray = require('stream-to-array'); const sendToWormhole = require('stream-wormhole'); const Controller = require('egg').Controller; const settings = require('../../config/settings'); class UploadController extends Controller { async post() { const { ctx } = this; let dir_name = ctx.params.dir_name const stream = await ctx.getFileStream(); let url = "" try { const parts = await toArray(stream); let data = Buffer.concat(parts); let file_md5 = md5(data) let file_name = `${file_md5}${path.extname(stream.filename)}` let file_path = path.join(this.config.baseDir, "app/public", dir_name, file_name) // 保存文件 // console.log(file_path) await fs.writeFile(file_path, data, (err) => { }); url = `http://${settings.addr}:${settings.port}/static/${dir_name}/${file_name}` } catch (err) { await sendToWormhole(stream); } ctx.body = { url: url }; } } module.exports = UploadController;
路由:
配置: // mode: stream
使用:
参考官方文档: // 有写法例子,在他的基础上加了md5而已
https://github.com/eggjs/egg-multipart
https://github.com/eggjs/examples/blob/master/multipart/app/controller/buffer.js