【问题标题】:How upload images and arrays on express server with Multer?如何使用 Multer 在 express 服务器上上传图像和数组?
【发布时间】:2021-02-10 17:37:45
【问题描述】:

我正在尝试使用 HTTP 帖子(角度)在我的快递服务器上“保存”产品(名称、描述、价格)、代码列表和图像列表。

JSON.stringify(product) // stringify the array that contains name description..
JSON.stringify(codes)
imageFiles: File[] // array of images

使用 for 循环,我将 imageFiles 的每个项目附加到 var FromData,然后附加其他 2 个字符串化数组。

我正在尝试更多解决方案来实现我的目标:

  1. 将存储在数组中的信息保存在数据库中
  2. 然后将图像保存在服务器上

用我正在使用 Multer 的文件解析 req:

案例一:

router.post("/newProduct", upload.array('images[]', 10), function (req, res, next) {
  // first: middleware is executed the images are loaded
  // in the req.body I find the other 2 arrays to store in the DB
  // but if something with the DB fails, I still have the images saved (I DONT WANT IT)
});

案例 B:

router.post("/newProduct",  function (req, res, next) {
  upload.array('images[]', 10)(req, res, next);
  // here i can't access req.body anymore because I'm outside multer that can parse what is stores in the request
});

关于它的一些想法??

【问题讨论】:

    标签: node.js express file-upload multer


    【解决方案1】:

    您应该在处理图片之前验证您的数据,因此如果您的数据验证失败,则不会上传图片。 这里有 2 个选项

    1. 使用 Multer Config 在 multer 保存文件之前验证数据。
    2. (更好的选择)创建一个用于数据验证的中间件,以便 multer 仅在您执行了所有数据验证并且您知道它不会失败时才上传。

    这里是 multer 单文件上传和多文件上传的示例,如果您需要选项 2,请正确配置 multer 和示例中间件

    const express = require('express');
    const multer = require('multer');
    
    // first create a multer config
    const StorageConfig = multer.diskStorage({
    
        destination: function (req, file, cb) {
            // here you can validate all data from your request object
            try{
                // some thing like following. and in case of failure of data validation raise a call back with error
                if(typeof req.body.ImageFor == "undefined"){
                    return cb(new Error('Uploading Image for  is Required, 1 for MAIN image, 2 for Thumbnale'))
                }
                else if(req.body.ImageFor !=1 && req.body.ImageFor!= 2){
                    return cb(new Error('Invalid value for ImageFor, 1 for MAIN image, 2 for Thumbnale'))
                }
                var dir="";
                // adjust your storage path according to your requirements
                // can be as simply as uploads/ 
                // (done forget to create the directory else MULTER will throw error)
                dir = 'uploads/' + req.body.ProductID + '/' + req.body.ImageFor + '/';
                cb(null, dir);   
    
            }
            catch(err){
                console.log('error', err);
            }
            
        },
        // define your file name the way you like. 
        filename: function (req, file, cb) {
            // save file as current UTC tile 
            //let extArray = file.mimetype.split("/");
            //let extension = extArray[extArray.length - 1];
            //cb(null,getUTCTime()+ '.'+ extension);
            cb(null,file.originalname);
        }
    });
    
    // define the File filters , what type of files you want to accept.
    const fileFilters=(req,file,cb)=>{
        if(file.mimetype==='image/jpeg' || file.mimetype ==='image/png'){
            cb(null, true);
        }
        else{
            cb(null, false);
        }
    }
    
    // lets create our multer objects 
    const Multerupload = multer({ storage: StorageConfig,fileFilter: fileFilters});
    
    // now here is your API Call 
    
    router.post('/UploadFile',Multerupload.single('imageFieldName'),(req,res,next) =>{
            // process your data here if needed    
    });
    
    //=========================================
    
    // Multer also supports Multi file upload 
    // so lets create a multi file upload in single call,
    // multer will need fields array with limit so lets define that 
    // following will allow uploading of 10 images of each (change fields according your call)
    var upLoadFields = [
        { name:'productMainImage', maxCount: 10 },
        { name: 'productSmallImage', maxCount: 10 },
        { name: 'productSideImage', maxCount: 10 },
        { name: 'productThumbnale', maxCount: 10 }
    ];
    
    // now lets create a multi upload API
    
    router.post('/UploadMulti',Multerupload.fields(upFields),(req,res,next) =>{
            // process your data here if needed    
    
    });
    

    我建议在 multer 上传/处理文件之前创建一个用于数据处理的中间件,在该中间件中您可以验证/保存/从 DB 等中获取数据,并且只有在您满意时才移动到 next() 和 multer将处理文件。

    这里是选项 2(中间件)的示例

    //====================
        // ######### Method 2 better way (I think)#########
        // ideally the data validation should be done in a middleware, 
        // 
        
        // so above multi-upload call will change to following 
    
        const ValidateData = require('../middlewares/Datavalidator');
    
        router.post('/UploadMulti',ValidateData,MultiuploadFile.fields(upFields),(req,res,next) =>{
        });
        
        //----------------- here is the simple how you will create a middlewere
        // Create a new file called Datavalidator in some directory, I am using middlewares as the directory name
        // and in the file do something like following 
        
        module.exports = (req,res,next) =>{
            var responseObject={};
            if(typeof req.body.ImageFor == "undefined"){
                // change the status according to your need, i am using 500 = internal server error just for example 
                responseObject.status = 500;
                responseObject.message= 'ImageFor is required';
                return res.status(responseObject.status).json(responseObject);
            }
            else if(!(req.body.ImageFor ==1 && req.body.ImageFor==2)){
                responseObject.status = 500;
                responseObject.message= 'ImageFor Value is in correct';
                return res.status(responseObject.status).json(responseObject); 
            }
    next();
        };
    

    【讨论】:

      【解决方案2】:

      使用 express-file-upload 。它更容易在 express 上维护上传功能。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-27
        • 2016-09-27
        • 2016-06-14
        • 2015-05-02
        • 1970-01-01
        • 2020-10-10
        • 2020-12-25
        • 2021-05-03
        相关资源
        最近更新 更多