簡體   English   中英

\"path\" 參數必須是字符串類型或 Buffer 或 URL 的實例。 從 nodejs 收到 undefined

[英]The \"path\" argument must be of type string or an instance of Buffer or URL. Received undefined from nodejs

我正在嘗試從 reactjs 獲取文件並作為參數發送到 Node.js 后端,以便在 API 中進行處理。 但它給了我這個錯誤。 這是代碼:

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));
            }
          });
        }
      }
    );

在前端,我這樣發送文件:

<Input type="file" name="voice" />

這是我的錯誤代碼:

    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'

我怎樣才能防止這個錯誤?

您需要 multer 進行多部分文件和上傳。 在前端添加這個

<form action="/voice" method="post" enctype="multipart/form-data">
  <input type="file" name="voice" />
</form>

在后端,

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
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM