简体   繁体   中英

File upload to server using NodeJs and Multer

I'm trying to upload a file to the server using NodeJs and Multer. But I'm unsuccessful. When I post the file from my front end I get the conditional statement as follow:

You must select at least 1 file.

The console.log(req.files) as per script below returns back an empty array [] .

Here below the userController.js

 const mysql = require('mysql'); const jwt = require('jsonwebtoken'); const bcrypt = require('bcryptjs'); const { promisify } = require('util'); const upload = require("../middleware/upload"); exports.update = async (req, res) => { message = ''; if (req.method == 'POST') { var post = req.body; var first_name = post.first_name; var last_name = post.last_name; if (req.files) { // console.log(req.files) try { await upload(req, res); console.log(req.files); if (req.files.length <= 0) { return res.send(`You must select at least 1 file.`); } return res.send(`Files has been uploaded.`); } catch (error) { console.log(error); if (error.code === "LIMIT_UNEXPECTED_FILE") { return res.send("Too many files to upload."); } return res.send(`Error when trying upload many files: ${error}`); }

Here my middleware upload.js

 const util = require("util"); const path = require("path"); const multer = require("multer"); var storage = multer.diskStorage({ destination: (req, file, callback) => { callback(null, path.join(`${__dirname}/../../upload`)); }, filename: (req, file, callback) => { const match = ["image/png", "image/jpeg", "application/pdf"]; if (match.indexOf(file.mimetype) === -1) { var message = `<strong>${file.originalname}</strong> is invalid. Only accept png/jpeg/pdf.`; return callback(message, null); } var filename = `${Date.now()}-bezkoder-${file.originalname}`; callback(null, filename); } }); var uploadFiles = multer({ storage: storage }).array("multi-files", 10); var uploadFilesMiddleware = util.promisify(uploadFiles); module.exports = uploadFilesMiddleware;
Here my user.js for the routing:
 const express = require('express'); const router = express.Router(); const userController = require('../controllers/userController'); router.post('/editcrew/:id',userController.update);

And my front end:

 <form class="row g-1 needs-validation" method="POST" action="/editcrew/{{this.id}}" encType="multipart/form-data" novalidate> </form> <input type="file" name="covid_19D" id="file_box" /> <div class="col-md-1 mt-5 d-grid"> <button class="btn btn-primary" type="submit">Submit</button> </div>

Any advice, suggestion, and direction on the correct path is highly appreciated THANKS!!

Your file input is outside of the form, so it's not part of what will be sent when the form is submitted.

Move it into the form instead:

<form class="row g-1 needs-validation" method="POST" action="/editcrew/{{this.id}}" encType="multipart/form-data" novalidate>
  <input type="file" name="covid_19D" id="file_box" />
</form>

in the userController.js, try calling upload middleware with then() instead of await :

const upload = require("../middleware/upload");


exports.update = async(req, res) => {

    if (req.method == 'POST') {

        var post = req.body;
        var first_name = post.first_name;
        var last_name = post.last_name;

        upload(req, res).then(() => {

            if (req.files) {

                if (req.files.length <= 0) {
                    return res.send(`You must select at least 1 file.`);
                }

                return res.send(`Files has been uploaded.`);
            }

        }).catch(error => {

            if (error.code === "LIMIT_UNEXPECTED_FILE") {
                return res.send("Too many files to upload.");
            }
            return res.send(`Error when trying upload many files: ${error}`);
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM