尝试发送blob对象到我的节点服务器。在客户端,我正在使用MediaRecorder录制一些音频,然后我想将文件发送到服务器进行处理。
saveButton.onclick = function(e, audio) {
var blobData = localStorage.getItem('recording');
console.log(blobData);
var fd = new FormData();
fd.append('upl', blobData, 'blobby.raw');
fetch('/api/test',
{
method: 'post',
body: fd
})
.then(function(response) {
console.log('done');
return response;
})
.catch(function(err){
console.log(err);
});
}
这是我的快车路线,它使用multer:
var upload = multer({ dest: __dirname + '/../public/uploads/' });
var type = upload.single('upl');
app.post('/api/test', type, function (req, res) {
console.log(req.body);
console.log(req.file);
// do stuff with file
});
但是我的日志没有返回任何东西:
{ upl: '' }
undefined
花了很长时间在这个所以任何帮助感激!
我只能运行你上面例子的最小配置,它对我来说工作得很好。
服务器:var express = require('express');
var multer = require('multer');
var app = express();
app.use(express.static('public')); // for serving the HTML file
var upload = multer({ dest: __dirname + '/public/uploads/' });
var type = upload.single('upl');
app.post('/api/test', type, function (req, res) {
console.log(req.body);
console.log(req.file);
// do stuff with file
});
app.listen(3000);
HTML文件在public
:
<script>
var myBlob = new Blob(["This is my blob content"], {type : "text/plain"});
console.log(myBlob);
// here unnecessary - just for testing if it can be read from local storage
localStorage.myfile = myBlob;
var fd = new FormData();
fd.append('upl', localStorage.myfile, 'blobby.txt');
fetch('/api/test',
{
method: 'post',
body: fd
});
</script>
前端的console.log(myBlob);
正在打印Blob {size: 23, type: "text/plain"}
。后端打印:
{}
{ fieldname: 'upl',
originalname: 'blobby.txt',
encoding: '7bit',
mimetype: 'text/plain',
destination: '/var/www/test/public/uploads/',
filename: 'dc56f94d7ae90853021ab7d2931ad636',
path: '/var/www/test/public/uploads/dc56f94d7ae90853021ab7d2931ad636',
size: 23 }
也可以尝试使用硬编码的Blob,如本例中用于调试目的。
不需要使用multer。在app.post()
中使用express.raw()
var express = require('express');
var app = express();
app.use(express.static('public')); // for serving the HTML file
app.post('/api/test', express.raw({type: "*/*"}), function (req, res) {
console.log(req.body);
// do stuff with file
});
app.listen(3000);