我正在尝试创建一个接收数据并将其保存到png文件的端点。这个PHP代码可以做到:
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// Get the data
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
// Remove the headers (data:,) part.
// A real application should use them according to needs such as to check image type
$filteredData=substr($imageData, strpos($imageData, ",")+1);
// Need to decode before saving since the data we received is already base64 encoded
$unencodedData=base64_decode($filteredData);
// Save file. This example uses a hard coded filename for testing,
// but a real application can specify filename in POST variable
$fp = fopen( 'test.png', 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
}
我是新来的,我有这个:
app.use (function(req, res, next) {
var data='';
req.setEncoding('utf8');
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
req.body = data;
next();
});
});
app.post('/upload', function(req, res){
var testData = req.body;
return res.send(testData);
});
我得到一个空白的物体。即使实际数据正在发布。有人能告诉我一个在express中编写上述代码的好方法吗?
由于
答案 0 :(得分:1)
所以从处理程序中取出它:
var fs = require('fs');
app.post('/upload', function(req, res){
var image = req.body;
var noHeader = image.substring(image.indexOf(',') + 1);
var decoded = new Buffer(noHeader, 'base64');
fs.writeFile('testfile.png', decoded, function(err){
res.send('done!');
});
});