Multer - how to handle files using upload.fields() once files have been submitted

时光怂恿深爱的人放手 提交于 2020-06-17 05:19:00

问题


I have been experimenting with Multer and was working on saving a movie document to MongoDB using Mongoose. After having the user submit an image in one input field and a video in a separate input field, I use multer's upload.fields() option to handle these files.

I want posterImageName to save the filename for 'myImage' and trailerVideoName to save the filename for 'myVideo', so that I can display the image and video when fetched from my database. When I try to set these filenames in my movie document and try to save it to my database, I get the following error: "Cannot read property 'filename' of undefined"

Here is my code:

const upload = multer({
    storage: multer.diskStorage({
        destination: (req, file, cb) => {
            cb(null, './public/uploads/')
        },

        filename: (req, file, cb) => {
            cb(null, `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`);
        },
    }),

    limits: {fileSize: 10000000000},
    fileFilter: (req, file, cb) => {
        // Allowed ext
        const filetypes = /jpeg|jpg|png|gif|mp4/;
        // Check ext
        const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
        // Check mimetype
        const mimetype = filetypes.test(file.mimetype);

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

    }
})

router.post('/movies', upload.fields([{name: 'myImage'}, {name: 'myVideo'}]), (req, res) => {
    const movie = new Movie({
        title: req.body.title,
        posterImageName: req.files[0].filename,
        trailerVideoName: req.files[1].filename
    })

    movie.save((error, movie) => {
        if (error) return console.error(error);
        console.log(`${movie.title} saved to movies collection`);
    });
})

I have tried searching for a good explanation on how to use upload.fields() but could not find any, as all the tutorials and forums I have seen talk about upload.single() or upload.array(). If you need other pieces of code, please let me know. All help is greatly appreciated :)


回答1:


It's mentioned in the README.md documentation of multer

  // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
  //
  // e.g.
  //  req.files['avatar'][0] -> File
  //  req.files['gallery'] -> Array
  //
  // req.body will contain the text fields, if there were any

Basically, the names of the fields correspond to the keys of req.files

    const movie = new Movie({
        title: req.body.title,
        posterImageName: req.files['myImage'][0].filename,
        trailerVideoName: req.files['myVideo'][0].filename
    })



回答2:


I was also having difficulties using upload.fields but I tried the above and it works but I can't upload just one field except the two field and also how can i upload using upload.array that's multiple files



来源:https://stackoverflow.com/questions/61979897/multer-how-to-handle-files-using-upload-fields-once-files-have-been-submitte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!