【问题标题】:multer req.files undefined with axios in reactmulter req.files undefined with axios in react
【发布时间】:2021-08-29 13:43:03
【问题描述】:

我想使用 axios 将 formData 发布到节点 js 路由,然后将图像文件保存到 images 文件夹中。我正在使用 multer 从 axios 读取多部分/表单数据。我从 req.body 接收到 productInfo 对象,这是正确的。这是我的代码:

const addNewProduct = () => {

        const newProduct = {
            name: name,
            cost: cost,
            size: size,
            color: color,
            material: material,
            discount: discount,
            description: description,
            category: category
        };

        const nulls  = Object.values(newProduct).filter(p => p === null);

        if(nulls.length === 0 && images.imageFiles) {
            let productFormData = new FormData();
            productFormData.append('productInfo', JSON.stringify(newProduct));
            productFormData.append('productImages', [...images.imageFiles]);
    
            const addUrl = "http://localhost:8080/cpnl/addproduct";
            axios({
                method: "POST",
                url: addUrl,
                data: productFormData,
                headers: { "Content-Type": "multipart/form-data" }
            })
                .then((response) => {
                    console.log(response.data.msg);
                })
                .catch((response) => {
                    console.error(response);
                });
        }else {
            Notiflix.Notify.Warning("Check your inputs!");
            console.log(nulls);
            console.log("product: \n" + JSON.stringify(newProduct));
        }
};

然后我使用 multer 在节点 js 中接收数据,如下所示:

multer 配置:

const storage = multer.diskStorage({
    destination: "./public/images",
    filename: (req, file, cb) => {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
});

const upload = multer({
    storage: storage,
    limits:{fileSize: 1000000},
    fileFilter: function(req, file, cb){
        checkFileType(file, cb);
    }
}).array("productImages");

function checkFileType(file, cb) {
  // Allowed ext
  const filetypes = /jpeg|jpg|png/;
  // Check ext
  const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
  // Check mime
  const mimetype = filetypes.test(file.mimetype);

  if(mimetype && extname){
    return cb(null,true);
  } else {
    cb('Error: Images Only!');
  }
}

多路路由:

router.post('/addproduct', async (req, res) => {
    upload(req, res, (err) => {
        if(err) {
            res.status(400).json({
                msg: err
            });
        } else {
            if(req.files == undefined) {
                res.status(400).json({
                    msg: "Error: No file selected! please contact the developer."
                });
            } else {
                //problem occures here
                console.log( "images: " + req.body.productImages + "\n");
                data = req.body.productInfo;
                res.status(200).json({
                    msg: "Files uploaded!"
                });
                console.log("data" + data);
            }
        }
    });
});

我在 req.body.productImages 中接收图像文件作为对象文件。 所有这些代码起初看起来都不错,但 multer 没有上传图像文件!
为什么图像在 req.body.productImages 中?
为什么它们不在 req.files 中?
这里发生了什么?

【问题讨论】:

    标签: node.js reactjs axios multer


    【解决方案1】:

    在您的 multer route 代码中,您需要按以下方式进行更改

    router.post('/addproduct', upload, async (req, res, next) => {/**
      YOUR LOGIC GOES HERE
    */}
    

    因为upload 是一个多引用并返回 express 中间件。因此,它将使用您期望 req.files 所需的值更新 req 对象。

    注意: req.body.productImages 存在是因为req 对象未被multer 处理

    【讨论】:

    • 对不起。我应该结束这个问题。感谢您的回答。我刚刚找到了解决方案并在描述中添加了新代码。
    猜你喜欢
    • 2018-08-19
    • 2018-01-26
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 2018-12-04
    相关资源
    最近更新 更多