Node.js Can';t将图像缓冲区转换为base64字符串
在我的服务器中,我收到一个对多部分表单数据的POST请求,其中我收到一个PNG图像文件。我使用Buffer.slice()获取原始PNG图像。但在试验格式化缓冲区时,我发现:Node.js Can';t将图像缓冲区转换为base64字符串,node.js,buffer,png,Node.js,Buffer,Png,在我的服务器中,我收到一个对多部分表单数据的POST请求,其中我收到一个PNG图像文件。我使用Buffer.slice()获取原始PNG图像。但在试验格式化缓冲区时,我发现: console.log(requestBody.compare(Buffer.from(requestBody.toString('base64')))); 此语句返回-1。(此处requestBody是格式化程序图像缓冲区) 我的疑问是,这个语句不应该返回0吗?因为我正在将同一个缓冲区转换为字符串,然后再转换回缓冲区
console.log(requestBody.compare(Buffer.from(requestBody.toString('base64'))));
此语句返回-1。(此处requestBody是格式化程序图像缓冲区)我的疑问是,这个语句不应该返回0吗?因为我正在将同一个缓冲区转换为字符串,然后再转换回缓冲区 我的代码:
const http = require('http');
const fs = require('fs');
const qs = require('querystring');
const path = require('path');
http.createServer(function ( request, response ) {
if ( request.method == 'GET' ) {
fs.readFile('./views/index.html', function ( error, data ) {
response.writeHead(200, {'Content-Type':'text/html'});
response.end(data);
});
} else if ( request.method == 'POST' ) {
let requestBody = null;
request.on('data', function( data ) {
if ( requestBody == null ) {
requestBody = data;
} else {
requestBody += data;
}
});
request.on('end', function( data) {
requestBody = Buffer.from(requestBody.slice(requestBody.indexOf('image/png') + 13, requestBody.lastIndexOf('------')-1));
console.log(requestBody.compare(Buffer.from(requestBody.toString('base64'))));
response.writeHead(200, {'Content-Type':'image/png'});
response.end(requestBody);
});
}
}).listen(3000);