Egg.js上传文件如何将Filestream转换成buffer
发布于 6 年前 作者 JamesGu14 4303 次浏览 来自 问答

在使用egg.js上传文件的时候,遇到一些问题:

  1. 先是上传到本地的时候,stream.pipe存储的时候常常文件还没保存完毕,程序就会开始继续运行下面的指令了。发现一个之前别人提的问题,貌似也没有结论。https://cnodejs.org/topic/58f8a3cb31e8c2bb1c3dcc18

  2. OK,既然填不了坑我就绕着走,存OSS,没问题。但是现在有个问题是,我需要在存OSS之前,把图片进行压缩,意味着在读完FileStream后,需要使用resize的库,修改图片后再上传。我的代码如下:

const Controller = require('egg').Controller

const sendToWormhole = require(‘stream-wormhole’) const resizeImg = require(‘resize-img’) async compare() { const stream = await this.ctx.getFileStream() if (!stream.truncated) { const name = this.ctx.helper.uuid() + path.extname(stream.filename) const fields = stream.fields let postResult try { // 在 // const buf = await resizeImg(new Buffer(stream._readableState.buffer.tail.data), {width: 300})

  postResult = await this.ctx.service.ali.postFace(name, stream)  // 这里是上传到OSS的代码
    } catch (err) {
        await sendToWormhole(stream)
        throw err
    }

就在const buf = await resizeImg(xxxx) 那行,不知道如何做才能将FileStream object转成buffer呢?

5 回复

@MiYogurt 多谢,搞定。

const toArray = require(‘stream-to-array’) const stream = await ctx.getFileStream(); const parts = await toArray(stream); 我这样使用后 得到的 parts 是一个空的数组 @JamesGu14 这个问题你有遇到吗?

我是暂时存到了本地

来自酷炫的 CNodeMD

const eos = promisify(require(‘end-of-stream’)); const fileStream = fs.createWriteStream(filepath); uploadStream.pipe(fileStream);

await eos(uploadStream);

回到顶部