我正在嘗試使用 formData將音頻檔案從我的react應用程式傳遞到Express后端,但是當我嘗試在后端檢索資料時,我一直未定義。
前端代碼:
var fd = new FormData();
fd.append('fname', 'test.webm');
fd.append('data', blob);
payload = {audioFile: fd};
axios.post('/translate-audio', payload, {headers: {'content-type': 'multipart/form-data'}})
后臺代碼:
app.use(cors());
app.use(express.json());
app.post('/translate-audio', async (req, res) => {
console.log(req.body.audioFile);
});
邊注:
當我console.log(payload.audioFile.get('data'));在前端運行時,我能夠看到該檔案:
File {name: 'blob', lastModified: 1636600689885, lastModifiedDate: Wed Nov 10 2021 19:18:09 GMT-0800 (Pacific Standard Time), webkitRelativePath: '', size: 10828, …}
lastModified: 1636600689885
lastModifiedDate: Wed Nov 10 2021 19:18:09 GMT-0800 (Pacific Standard Time) {}
name: "blob"
size: 10828
type: "audio/webm;codecs=opus"
webkitRelativePath: ""
任何幫助是極大的贊賞。我只需要將 blob 正確傳遞到后端,因此其他不使用 formData 的替代方法也將有所幫助。另外,有什么好的方法可以反過來(從服務器向前端發送音頻 blob)?
uj5u.com熱心網友回復:
您無法序列FormData化為 JSON。FormData直接發送作為您的請求資料并使用像Multer這樣的中間件在服務器端處理它
前端
const fd = new FormData()
fd.append("audioFile", blob, "test.webm")
// Do not customise the content-type header.
// See https://stackoverflow.com/a/68643919/283366
axios.post("/translate-audio", fd)
表達
const multer = require("multer")
const storage = multer.memoryStorage() // or use disk storage
const upload = multer({ storage })
app.post('/translate-audio', upload.single("audioFile"), async (req, res) => {
console.log(req.file);
// see https://github.com/expressjs/multer#file-information
});
另外,有什么好的方法可以反過來(從服務器向前端發送音頻 blob)?
如果您正在處理磁盤上的檔案,請使用res.sendFile(),否則res.send()能夠處理緩沖區。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/355648.html
上一篇:Java圖形:通過2D線連接點
