【问题标题】:React: Multer image and data upload with using firebase function, node multerReact: 使用 firebase 功能、节点 multer 进行 Multer 图像和数据上传
【发布时间】:2020-12-24 00:00:24
【问题描述】:

基本上,我正在使用 firebase 功能并使用节点托管并做出反应。我可以上传图片由How to perform an HTTP file upload using express on Cloud Functions for Firebase (multer, busboy)提供 但是如何同时上传图片和数据呢?

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

【问题讨论】:

    标签: node.js reactjs firebase multer


    【解决方案1】:

    您的客户端代码看起来不错。
    在服务器端,您可以告诉 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"]

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-07
      • 2020-07-16
      • 1970-01-01
      • 2018-09-17
      • 2016-06-16
      • 1970-01-01
      • 2021-05-02
      • 2018-12-16
      相关资源
      最近更新 更多