【问题标题】:uploading files from react to node js with multer使用multer从react上传文件到node js
【发布时间】:2021-08-29 12:57:54
【问题描述】:

我想从 axios 这样发布的 react 表单数据中上传文件。

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 将图像上传到图像文件夹。这是我的代码:

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", 5);

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!');
  }
}

//receive form data from front-end and add new product to database
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 {
                data = req.body.productInfo;
                res.status(200).json({
                    msg: "Files uploaded!"
                });
                console.log( "images: " + req.files);
                console.log("data" + data);
            }
        }
    });
});

第一个问题:我在 req.body.productImages 中而不是在 req.files 中获取图像文件

第二个问题:当我发送请求时,节点js会抛出这个错误:

TypeError:上传不是函数

为什么一切都搞砸了!?

编辑:我重新启动了服务器,现在我正在获取数据,但没有上传文件。没有显示错误。

更新:修复了第二个问题

【问题讨论】:

    标签: node.js reactjs multipartform-data multer


    【解决方案1】:

    第一个问题:您在上传功能中使用了.array("productImages", 5);。使用.array("files", 5);获取req.files中的文件。

    第二个问题:我猜你的代码中有一些拼写错误upload(req, res, (err)... 有一个额外的括号应该只有upload(req,res,err )...

    【讨论】:

    • req.files 未定义,数组方法的第一个参数必须与图像文件字段相同,在我的例子中是 productImages。第二个问题是我必须在上传函数中定义数组或单个选项。我编辑了问题。
    • 我的问题是图像文件在 req.body.productImages 中,而不是在 req.files 中。我认为 multer 正试图从 req.files 中检索它们,但没有可用的。我添加了一个 if 语句来检测未定义的错误。即使 req.files 未定义,它也不会触发。
    • 这里有个小修正,把这里productImage的名字.array("productImages", 5);改成.array("files", 5);。在您的 multer 上传功能中更改此设置,您将获得 req.files 中的文件
    • 我改了。不幸的是,它不起作用。
    • console.log(req.body.productImages) 在控制台打印这个 => [object File],[object File]
    猜你喜欢
    • 2020-09-04
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 2020-07-16
    • 2018-03-31
    • 2021-04-09
    • 2018-02-28
    相关资源
    最近更新 更多