I am trying to get a file from reactjs and send as param to Node.js backend for processing in an API. But it gives me this error. Here is the code:
const FormData = require("form-data");
const fs = require("fs");
const model = "tr-8";
const formd = new FormData();
const { voice } = req.body;
const file = voice;
const timeout = 360000;
formd.append("model", model);
formd.append("files[]", fs.createReadStream(voice, { autoClose: true }));
const request = formd.submit(
`${Process.env.API}` + model,
function (err, rs) {
if (err) {
console.log("formd.submit error " + voice);
console.log(err);
}
if (rs) {
var resp = Buffer.from([]);
rs.on("error", function (err) {
console.log("formd.submit on error " + voice);
console.log(err);
});
rs.on("close", function () {
console.log("close " + voice);
});
rs.on("data", function (chunk) {
resp = Buffer.concat([resp, chunk]);
});
rs.on("end", function () {
console.log("end " + voice);
const resputf8 = resp.toString("utf8");
const recognitionResult = JSON.parse(resputf8);
const speech = recognitionResult.JsonResult;
if (speech.error) {
console.log("transcript error " + speech.error + " " + voice);
} else {
console.log(JSON.stringify(speech, null, 2));
}
});
}
}
);
And In the frontend, I send the file like that:
<Input type="file" name="voice" />
This is my error code:
at ReadStream._construct (node:internal/fs/streams:64:17)
at constructNT (node:internal/streams/destroy:288:25)
at processTicksAndRejections (node:internal/process/task_queues:80:21) {
code: 'ERR_INVALID_ARG_TYPE'
How can i prevent this error?
You need multer for multipart files and uploads. In frontend add this
<form action="/voice" method="post" enctype="multipart/form-data">
<input type="file" name="voice" />
</form>
and in backend,
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
app.post('/voice', upload.single('voice'), function (req, res, next) {
// req.file is the `voice` file
const voice = req.file
// req.body will hold the text fields, if there were any
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.