如何使用nodejs和react将blob上传到服务器

问题描述 投票:0回答:1

我已经录制了一个文件。现在我将录制的文件作为 blob 获取,我想将其上传到服务器,但每当我发出请求时,我都会得到

400 bad request
。如果我能得到帮助,我将非常感激

这里是带有生成的blob的记录文件功能

record = () => {
let preview = document.getElementById("preview");
let recording = document.getElementById("recording");

this.setState({ loading: true });

let recordingTimeMS = 2000;
navigator.mediaDevices
  .getUserMedia({
    video: true,
    audio: true,
  })
  .then((stream) => {
    preview.srcObject = stream;
    preview.captureStream =
      preview.captureStream || preview.mozCaptureStream;
    return new Promise((resolve) => (preview.onplaying = resolve));
  })
  .then(() => this.startRecording(preview.captureStream(), recordingTimeMS))
  .then(async (recordedChunks) => {
    let recordedBlob = new Blob(recordedChunks, {
      type: "video/webm",
    });
    recording.src = URL.createObjectURL(recordedBlob);

    this.sendVideoToAPI(recordedBlob);
  })
  .catch((err) => console.log(err));

};

这是上传到服务器的功能

sendVideoToAPI = async (blob) => {
const formData = new FormData();
formData.append("dataFile", blob);
console.log(blob);
Axios({
  method: "post",
  url: "http://localhost:8000/upload",
  headers: {
    "X-Requested-With": "XMLHttpRequest",
    "Access-Control-Allow-Origin": "*",
  },
  data: {
    file: formData,
  },
})
  .then((response) => {
    console.log(response);
  })
  .catch((err) => {
    console.log(err);
  });

};

这是我的server.js

app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/uploads", express.static("uploads"));
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads");
  },
  filename: function (req, file, cb) {
    cb(
      null,
      `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`
    );
  },
});
var upload = multer({ storage: storage });
app.post("/upload", upload.single("dataFile"), (req, res, next) => {
  const file = req.file;
  if (!file) {
    return res.status(400).send({ message: "Please upload a file." });
  }
  return res.send({ message: "File uploaded successfully.", file });
});
app.get("/", (req, res) => {
  res.send("Giphy Chat Server is running successfully");
});

提前谢谢您

javascript node.js reactjs axios multer
1个回答
0
投票

在发送到服务器的上述数据中缺少一些内容。

  1. formdata 标头丢失。
  2. 您通过首先附加到数据文件然后再次在文件字段中发送它来使事情变得复杂。我不知道您正在创建的结构的相关性。

这是我进行上传的更改。

第一个上传到服务器的代码。

    const uploadVideo = useCallback(() => {
    if (recordedChunks.length) {
      const blob = new Blob(recordedChunks, {
        type: "video/webm",
      });
      const formData = new FormData();
      formData.append("file", blob);
      console.log("blobdata",blob);
      console.log("Request", formData);
      const url = 'http://localhost:8000/upload';

      // Send the POST request using Axios
      Axios.post(url, formData, {
        headers: {
          "Content-Type": "multipart/form-data", // Include proper headers for FormData
        },
      })
      .then((response) => {
        console.log(response);
      })
      .catch((err) => {
        console.log(err);
      });
      setRecordedChunks([]);
    }
  }, [recordedChunks]);

并在服务器上使用 multer 存储文件,如下所示。

app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/uploads", express.static("uploads"));
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads");
  },
  filename: function (req, file, cb) {
    cb(
      null,
      `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`
    );
  },
});
var upload = multer({ storage: storage });
app.post("/upload", upload.single("file"), (req, res, next) => {
  const file = req.file;
  console.log("fileData",file);
  if (!file) {
    return res.status(400).send({ message: "Please upload a file." });
  }
  return res.send({ message: "File uploaded successfully.", file });
});
© www.soinside.com 2019 - 2024. All rights reserved.