码迷,mamicode.com
首页 > Web开发 > 详细

egg.js上传文件到本地

时间:2018-07-16 00:57:53      阅读:779      评论:0      收藏:0      [点我收藏+]

标签:ini   ror   await   res   load   pip   div   dir   turn   

‘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.碎觉

egg.js上传文件到本地

标签:ini   ror   await   res   load   pip   div   dir   turn   

原文地址:https://www.cnblogs.com/qq735675958/p/9315694.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!