我正在尝试将上传图像中的一些二进制数据更改为base64,以便我可以使用它来显示图像。 但是极致给了我这个错误:
TypeError: Cannot read property 'on' of undefined
我不明白,当我发布时我也使用.on事件,它工作正常。 除此之外,我想知道我是否正确地更改数据。
请注意我对节点很新:)
我如何保存上传的图片(POST)
// Post to profile page
router.post('/', function(req, res, next) {
var busboy = new Busboy({ headers: req.headers });
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
var conn = mongoose.createConnection('192.168.99.100:32773');
conn.once('open', function () {
var gfs = Grid(conn.db);
var writestream = gfs.createWriteStream({
filename: filename,
content_type: mimetype,
mode: 'w',
metadata: {
belongs_to: req.session.passport.user
}
});
file.pipe(writestream);
writestream.on('close', function(file){
res.render('profile', {
user: req.user,
message: req.flash('uploadMessage', 'Your image has been uploaded successfully!')
})
})
})
})
req.pipe(busboy);
});
在这里,我尝试获取图像并将二进制数据转换为base64(GET)
// GET to index
router.get('/', function(req, res){
var conn = mongoose.createConnection('192.168.99.100:32773');
conn.once('open', function () {
var gfs = Grid(conn.db);
var readstream = gfs.createReadStream({
filename: 'kittendj.jpg'
});
readstream.pipe();
readstream.on('open', function(chunk){
bufs.push(chunk);
})
readstream.on('close', function(){
var bufs = [];
var fbuf = Buffer.concat(bufs);
var base64 = (fbuf.toString('base64'));
res.render('index', {
isAuthenticated: req.isAuthenticated(),
user: req.user,
imageSrc: '<img src="data:image/jpeg;base64,' + base64 + '">'
})
})
})
});
我检查了资源:
答案 0 :(得分:1)
我也在寻找从gridfs读取图像的解决方案,我正在使用grid-fs strem
这是我找到的解决方案,希望它对您有所帮助。
//设置gridfs
SELECT * table t1 left join table2 t2 on t2.someid = t1.someid WHERE t1.ItemName = exampleItem
//将图像写入mongo
import mongoose from 'mongoose';
import Grid from 'gridfs-stream';
const db = mongoose.connection.db;
const mongoDriver = mongoose.mongo;
const gfs = new Grid(db, mongoDriver);
//将图片读取到mongo
const writeStream = gfs.createWriteStream({
filename: 'test.png',
content_type: 'image/png',
});
fs.createReadStream(filePath).pipe(writeStream);
writeStream.on('close', (gfsFile) => {
// remove the original file
fs.unlink('test.png');
// this is the information, and _id is the id
console.log(gfsFile);
});
答案 1 :(得分:0)
请检查我创建的Github回购以上传图片并将结果作为base64返回。 https://github.com/houssem-yahiaoui/fileupload-nodejs