1

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

我检查的资源:

4

2 回答 2

2

我也在寻找从 gridfs 读取图像的解决方案,我正在使用 grid-fs strem

这是我找到的解决方案,希望对您有所帮助。

//设置gridfs

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

// 将图像读取到 mongo

const readstream = gfs.createReadStream({
  _id: id,
});

const bufs = [];
readstream.on('data', function (chunk) {
  bufs.push(chunk);
});
readstream.on('end', function () {
  const fbuf = Buffer.concat(bufs);
  const base64 = fbuf.toString('base64');
  console.log(base64);
});
于 2016-07-12T10:03:28.890 回答
0

请检查我创建的这个 Github 存储库以上传图像并将结果返回为 base64。 https://github.com/houssem-yaahiaoui/fileupload-nodejs

于 2017-07-27T20:07:23.627 回答