egg.js上传文件到本地
'use strict'; const Service = require('egg').Service; const fs = require('fs'); const path = require('path'); const sendToWormhole = require('stream-wormhole'); class UploadService extends Service { async index() { const ctx = this.ctx; const stream = await ctx.getFileStream(); const fileName = stream.filename; let target = path.join(this.config.baseDir, `app/public/comfiles/${stream.filename}`); const result = await new Promise((resolve, reject) => { const remoteFileStream = fs.createWriteStream(target); stream.pipe(remoteFileStream); let errFlag; remoteFileStream.on('error', err => { errFlag = true; sendToWormhole(stream); remoteFileStream.destroy(); reject(err); }); remoteFileStream.on('finish', async () => { if (errFlag) return; resolve({ fileName, name: stream.fields.name }); }); }); return result; } } module.exports = UploadService;
弄了一个下午,终于弄清楚了,MD.碎觉
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步