React:使用 firebase 函数、node multer 上传多张图像和数据

React: Multer image and data upload with using firebase function, node multer

基本上我使用的是 firebase 函数并使用节点托管并做出反应。我可以上传由 提供的图片 但是如何同时上传图片和数据呢?

export const addProduct = (product, imageUrl) => {
  return (dispatch) => {
    return new Promise((resolve, reject) => {
      const fileData = new FormData();
      fileData.append("imageUrl", imageUrl);
      fileData.append("productData", product);
      axios({
        method: "post",
        url: "/api/products/add-product",
        data: fileData,
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });
    });
  };
};

NodeJS

const router = express.Router();
const Busboy = require("busboy");

router.post("/api/products/add-product", async (req, res, next) => {
  if (req.method === "POST") {
    const busboy = new Busboy({ headers: req.headers });
    const uploads = {};
    busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
      console.log(
        `File [${fieldname}] filename: ${filename}, encoding: ${encoding}, mimetype: ${mimetype}`
      );
    });
  }
});

您的 client-side 代码看起来没问题。
在 server-side 上,您可以告诉 busboy 提取字段和文件:

const fields = {};
const files = [];
const busboy = new Busboy({headers: req.headers});
busboy.on("field", (key, value) => (fields[key] = value));
busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {/*...*/});
busboy.end(req.rawBoy);

这样您可以稍后在您的代码中访问 fields["productData"]

请注意,您需要使用 rawBody 来访问 Cloud Functions 中未解析的正文:https://firebase.google.com/docs/functions/http-events#read_values_from_the_request