使用Multer + Node JS上传多个不同的文件 - Postman

时间:2018-01-25 22:58:17

标签: node.js postman multer

是否可以使用multer + node JS将两个不同的文件(不同的扩展名)上传到不同的文件夹中。 multer(1.3.0)。

我收到错误:"意外字段"

//uploading content code here

   router.post('/v1/uploads', function(req, res){

  //uploading the cover
  //set storage engine for COVER
  var storage = multer.diskStorage({
    destination : './uploads/covers/',
    filename: function(req, file, callback){
      callback(null, randomString.generate(10) + "_"+ Date.now() + path.extname(file.originalname));
    }
  });

  //init upload for cover
  var upload = multer({
    storage: storage,
    limits:{fileSize: 50 * 1024 * 1024},
    fileFilter: function(req, file, callback) {
      checkFileTypeCover(file,callback)
    }
  }).single('artwork');

  upload(req,res, (err) => {
    if(err){
      res.json({
        success: false,
        message: 'upload failed cover with an error : '+err
      });
    }else{
      if(req.file == 'undefined'){
        res.json({
          success: false,
          message: 'failed to upload the file on the server for cover'
        });
      }else{

        console.log('we have uploaded an image');

        multer = '';

        var storage2 = multer2.diskStorage({
          destination : './uploads/content/',
          filename: function(req, file, callback){
            callback(null, randomString.generate(10) + "_"+ Date.now() + path.extname(file.originalname));
          }
        });


        //init upload for cover
        var upload2 = multer2({
          storage: storage2,
          limits:{fileSize: 50 * 1024 * 1024},
          fileFilter: function(req, file, callback) {
            checkfile(file,callback)
          }
        }).single('pdf');

        //upload image successfully, then upload pdf with new cover name
        //uploading the pdf

        upload2(req, res, (err) => {
          if(err){
            res.json({
              success: false,
              message: 'upload failed pdf with an error : '+err
            });
          }else{

            if(req.file == 'undefined'){
              res.json({
                success: false,
                message: 'failed to upload the file on the server'
              });
            }else{

              console.log('we have uploaded a pdf');

                /*

                //pdf file url for the content
                var pdf_url = req.file.filename;
                var title = req.body.title;
                var description = req.body.description;
                var free = req.body.free;
                var content_type = req.body.content_type;
                var category = req.body.category;
                var publisher = req.body.publisher;

                var newzine = new Newzine();
                newzine.title = title;
                newzine.description = description;

                if(free != null){
                  newzine.free = free;
                }
                if(content_type !=null){
                  newzine.content_type = content_type;
                }
                newzine.category = category;
                newzine.publisher = publisher;
                newzine.cover_url = 'no_image.png';
                newzine.pdf_url = pdf_url;

                //save the newzine on the mongo db database
                newzine.save(function(err){
                  if(err){
                    res.json({
                      success: false,
                      message: 'uploaded failed',
                      error: err
                    });
                  }else{
                    res.json({
                      success: true,
                      message: 'file uploaded successful'
                    });
                  }
                });
              }
          }  
        }); 
      }
    }
  });   

});

以下我检查图像和封面

var storage = multer.diskStorage({
 destination : './uploads/content/',
 filename: function(req, file, callback){
 callback(null, randomString.generate(10) + "-"+  Date.now()+path.extname(file.originalname));
 }
});

var upload = multer({
 storage: storage,
 limits:{fileSize: 50 * 1024 * 1024},
 fileFilter: function(req, file, callback) {
 checkFileTypePDF(file,callback)
 }
}).single('pdf');

 //check file type here for pdf
  function checkFileTypePDF(file, callback){
  // Allow only PDF extensions
   const fileTypes = /pdf|PDF/;
  //check extension
  const extname = fileTypes.test(path.extname(file.originalname).toLowerCase());
  //check mime type
  const mimetype = fileTypes.test(file.mimeType);

 if(extname){
   return callback(null,true);
 }else{
  callback('only pdf is allowed');
 }
}

//check file type here for cover
 function checkFileTypeCover(file, callback){
 // Allow only Image extensions
 const fileTypes = /jpg/;
 //check extension
 const extname =  fileTypes.test(path.extname(file.originalname).toLowerCase());
 console.log('the ext name is '+extname);
 //check mime type
 const mimetype = fileTypes.test(file.mimeType);
 console.log('the mimetype is '+mimetype);

 if(extname){
   return callback(null,true);
 }else{
  callback('only images are allowed');
  }
}

我使用邮递员上传图片和pdf,但邮递员失败,因为它不允许同时上传两个文件。一次只能上传一个文件。

2 个答案:

答案 0 :(得分:0)

我想你可以上传你的代码。 我将在这里发布一个非常通用的方法供您参考。无论如何,multer至少根据其默认设置并不介意多次上传或扩展。 示例前端代码:

<form action="PathOfYourChoice" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="ANY_NAME_YOU_WANT" id="fileToUpload" multiple="">
<input type="submit" value="Upload Image" name="submit">
</form>

使用此表单可以多次上传任何文件扩展名。请注意,您只需要在html标记中包含多个属性(无需任何值)。

在后端,提供存储配置,例如

var storage = multer.diskStorage({//further options to be specified after 
discussion
destination: function(req, file, callback) {
    callback(null, destination_fileupload(a variable,you should set the 
path))
},
filename: function(req, file, callback) {
    //filename schema has to be changed.Further decision pending on naming 
scheme
    callback(null, Date.now()+"-"+file.originalname)
}
}); 

在后端的路线上,例如

router.post("/PathOfYourChoice",function(req,res){
var upload = multer({
    storage: storage
    }).array('ANY_NAME_YOU_WANT'); //use .singleif you want only single file 
upload . Al
upload(req,res,function(err){
if(err)
    throw err;
res.send("files uploaded")
})

需要注意的一点是.array方法中的字符串必须与您在表单html中为input元素指定的名称相同。您在表单操作属性和路径路径中指定的路径也是如此。

答案 1 :(得分:0)

您可以遵循以下方法:

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        let filextPos = file
                .originalname
                .lastIndexOf('.'),
            filext = file
                .originalname
                .substring(filextPos)

        if (filext === 'jpg') {
           cb(null, './public/images/jpgs/')
        } else {
           cb(null, './public/images/pngs/')
        }
    }
});

const uploader = multer({storage: storage}).single('img');

我们在这里做的是根据文件(图像)扩展名更改默认上传路径。

此外,我们使用像这样的上传器中间件,

app.post('/uploadImage', uploader, function(req, res) {
   //file uploaded and callback received.
})