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.碎覺


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM