gpt4 book ai didi

javascript - 将缓冲区从 ReadStream 更改为实际文件

转载 作者:太空宇宙 更新时间:2023-11-04 01:40:46 24 4
gpt4 key购买 nike

所以我有这个代码:

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 () {
resolve(file);
});
});
}

我这样调用它:

Account.findById(req.params._id)
.then(async account => {
const file = await functions.downloadFile(account.employer.logo);
res.render('users/employer/booth', {
title: 'Employer Booth',
user: req.user,
postings: postings,
employer: account.employer,
event: event,
logo: logo,
});
});

如何将此文件保存到服务器并将其作为图像提供,或者只是将其发送到 View 并在 <img> 中显示它标签?

我尝试做这样的事情:

read_stream.on('open', function () {
var imgFile = fs.createWriteStream(`/public/images/logos/${file_id}.jpg`);
var write_stream = read_stream.pipe(imgFile);
read_stream.pipe(res);
});
read_stream.on('error', e => {
console.log(e);
});

但这无法读取保存的文件,并且该文件没有保存在任何地方。

最佳答案

好吧,这救了我的命:https://youtu.be/pXHOF4GWuZQ 。这是最终的代码:

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);
});
});
}

关于javascript - 将缓冲区从 ReadStream 更改为实际文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53073122/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com