我试图获取图像,应用转换并将其保存在像mongodb这样的数据库中。她是我的代码
var stor = function(inStream, sizeType) {
console.log('entering stor function');
var hashCode = '';
var img = new Buffer(1024 * 1024 * 5 * 1.1, 'binary'); //5mb size + 10% space
var hash = crypto.createHash('sha1');
inStream.on('data', function (chunk){
Buffer.concat([img, chunk]);
hash.update(chunk);
});
inStream.on('end', function() {
hashCode = hash.digest('hex');
var retUrl = "http://playground.com/" + hashCode;
//post this url using requests, set encoding : binary
});
};
server.post('/resize', function(req, res) {
req.accepts('application/json');
console.log('received a resize request for image =', req.body.host + req.body.path);
var request = requests.get({
url: req.body.url,
headers: {'accept-encoding': 'gzip'}
});
//error handling
request.on('response', function (response) {
console.log('succesfully fetched image...');
response.setEncoding('binary');
//save original in stor
stor(response, 'original');
res.writeHead(201);
res.send();
});
});
module.exports = server;
当我这样做时,我从互联网上收到一些图像,然后将其保存在我的数据库中供将来使用,数据库中保存的图像数据不是我存储的原始图像。它是腐败的。我已经将问题缩小到函数存储中的数据I缓冲区的编码(变量' img')。我这样做是通过直接将数据从响应传递到post到数据库调用。我不能为了我的目的这样做,因为我需要计算图像的哈希值。
我想知道我的假设是否正确。
我认为这些假设中的一个或全部都是错误的,因为我只从数据库中找回损坏的数据。
答案 0 :(得分:0)
问题在于我使用的是exec。 Exec输出一个缓冲区。使用spawn解决了这个问题。 Spawn输出 STREAM ,正确处理二进制文件。当然,我也将编码设置为二进制。