gpt4 book ai didi

javascript - 使用 fetch、multer、express 将 blob 数据发送到 Node

转载 作者:IT老高 更新时间:2023-10-28 23:19:11 27 4
gpt4 key购买 nike

尝试将 blob 对象发送到我的 Node 服务器。在客户端,我正在使用 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);

public中的HTML文件:

<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,如本示例中用于调试目的。

关于javascript - 使用 fetch、multer、express 将 blob 数据发送到 Node ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39677993/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com