Changing a buffer from a ReadStream into an actual file

后端 未结 1 1345
说谎
说谎 2020-11-30 15:00

So I have this code:

downloadFile(file_id) {
    return new Promise((resolve, reject) => {
        var mongoose = require(\'mongoose\');
        var Grid          


        
相关标签:
1条回答
  • 2020-11-30 15:18

    Ok this saved my life: https://youtu.be/pXHOF4GWuZQ. This is the final code:

    downloadFile(file_id) {
        return new Promise((resolve, reject) => {
            var mongoose = require('mongoose');
            var Grid = require('gridfs-stream');
            var fs = require('fs');
    
            mongoose.connect(config.db, {useNewUrlParser: true},).catch(e => console.log(e));
            var conn = mongoose.connection;
            Grid.mongo = mongoose.mongo;
            var gfs = Grid(conn.db);
            console.log('downloadfile', file_id);
            var read_stream = gfs.createReadStream({_id: file_id});
            let file = [];
            read_stream.on('data', function (chunk) {
                file.push(chunk);
            });
            read_stream.on('error', e => {
                console.log(e);
                reject(e);
            });
            return read_stream.on('end', function () {
                file = Buffer.concat(file);
                const img = `data:image/png;base64,${Buffer(file).toString('base64')}`;
                resolve(img);
            });
        });
    }
    
    0 讨论(0)
提交回复
热议问题