将缓冲区从 ReadStream 更改为实际文件 [英] Changing a buffer from a ReadStream into an actual file
本文介绍了将缓冲区从 ReadStream 更改为实际文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有这个代码:
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,
});
});
如何将此文件保存到服务器并将其作为图像提供,或者只是将其发送到视图并在 <img>
标签中显示?
How can I either save this file to the server and serve it as an image, or just send it to the view and show it in an <img>
tag?
我尝试做这样的事情:
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);
});
但是这无法读取保存的文件,并且文件没有保存在任何地方.
But this wasn't able to read the saved file, and the file wasn't saved anywhere.
推荐答案
好吧,这救了我一命:https://youtu.be/pXHOF4GWuZQ.这是最终代码:
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);
});
});
}
这篇关于将缓冲区从 ReadStream 更改为实际文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文