首页 > 解决方案 > 如何使用 Axios + 文本字段数据发送文件

问题描述

我已经在这个问题上停留了几天,我正因为沮丧而拉扯我的头发。我正在尝试使用 axios 发送文本字段等表单数据以及图像:

前端:

    handleChange = (e) => {
        this.setState({ [e.target.name]: e.target.value });
      };

handleSubmit = (e) => {
            e.preventDefault();
            const formData = new FormData();
            const img = e.target.files[0];
            formData.append("img", img, img.name);
            console.log(formData);
            this.props.postMe(
              {
                body: this.state.body,
                reqType: this.state.reqType,
                location: this.state.location,
              },
              formData
            );
          };


        <form onSubmit={this.handleSubmit}>
                      <TextField
                        name="body"
                        type="text"
                        onChange={this.handleChange}
                      />
                      <TextField
                        name="reqType"
                        type="text"
                        onChange={this.handleChange}
                      />
                      <TextField
                        name="location"
                        type="text"
                        onChange={this.handleChange}
                      />
                      <input
                        type="file"
                        name="img"
                        hidden
                        onChange={this.handleSubmit}
                      />
                    </form>

后端:

exports.postme = (req, res) => {

  const newRex= {
    body: req.body.body,
    reqType: req.body.reqType,
    location: req.body.location,
  };

  const BusBoy = require("busboy");
  const path = require("path");
  const os = require("os");
  const fs = require("fs");
  const busboy = new BusBoy({ headers: req.headers });

  let imageFileName;
  let imageToBeUploaded = {};

  busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
    if (mimetype !== "image/jpeg" && mimetype !== "image/png") {
      return res.status(400).json({ error: "Wrong file type submitted" });
    }
    const imageExtension = filename.split(".")[filename.split(".").length - 1];
    imageFileName = `${Math.round(
      Math.random() * 100000000
    )}.${imageExtension}`;
    const filepath = path.join(os.tmpdir(), imageFileName);
    imageToBeUploaded = { filepath, mimetype };
    file.pipe(fs.createWriteStream(filepath));
  });
  busboy.on("finish", () => {
    admin
      .storage()
      .bucket()
      .upload(imageToBeUploaded.filepath, {
        resumable: false,
        metadata: {
          metadata: {
            contentType: imageToBeUploaded.mimetype,
          },
        },
      })
      .then(() => {
        const imgUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imageFileName}?alt=media`;
        db.collection("requests")
          .add(newRequest)
          .then((doc) => {
            db.doc(`/requests/${doc.id}`).update({ imgUrl });
            const res = newRex;
            res.Id = doc.id;
            res.imgUrl = imgUrl ;
            return res.json(newRex);
          });
      })
      .catch((err) => {
        res.status(500).json({ error: "Something went wrong" });
        console.error(err);
      });
  });
  busboy.end(req.rawBody);
};

在我的后端,如果我只单独实现上传图像部分,它和文本部分一样工作,但是由于某种原因,当我将图像和文本字段数据组合在一起时它会失败?

非常感谢任何帮助或建议!

标签: node.jsreactjsgoogle-cloud-firestoreaxiosbusboy

解决方案


推荐阅读