我正在尝试将一些二进制数据从我上传的图像更改为 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 + '">'
})
})
})
});
我检查的资源: