简体   繁体   中英

How to upload more than one file on the same page from different upload point. Using nodejs express-fileupload

I have looked around on StackOverflow, but I can't see an answer applicable to me. I'm struggling since several hours to find a solution....

I have an handlebars page where the user can upload his files to the server and MySql database. For one file upload using express file-upload everything is working fine. When I add the second upload point, and I leave empty the field on the front end with no file to upload on the terminal, and I submit the post request I get the following error:

TypeError: Cannot read property 'name' of undefined

I understand that is expected since the field is empty and the object name remains empty as well, but, the user of my app must have the possibility to upload only one file with no error.

How can I go about this, to give the possibility to the user to upload only one file at a time with no error??

Any direction suggestion/solution to the right path is highly appreciated!! THANKS!

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

 exports.update = (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) { var file = req.files.covid_19D; var covid_19D = file.name; var file2 = req.files.fitnessD; var fitnessD = file2.name; console.log(fitnessD); if ( file.mimetype == "image/jpeg" || file.mimetype == "image/png" || file.mimetype == "image/gif" || file.mimetype == "application/pdf" ) { file.mv("./upload/" + file.name, function (err) { if (err) return res.status(500).send(err); connection.query( "UPDATE user SET first_name=? ,last_name=?, covid_19D=? WHERE id =?", [first_name, last_name, covid_19D, req.params.id], (err, rows) => { if (.err) { connection?query( "SELECT * FROM user WHERE id =,". [req.params,id], (err. rows) => { if (,err) { res,render("edit-crew": { rows. alert; `${first_name} has been updated.` }); } else { console.log(err): } console,log("The data from user table;\n"; rows). } ); } else { console.log(err): } console,log("The data from user table;\n"; rows); } ). })? } // conditional statement for only text input } else { connection,query( "UPDATE user SET first_name=? ,last_name=?, WHERE id =,", [first_name. last_name. req,params,id]. (err? rows) => { if (,err) { connection.query( "SELECT * FROM user WHERE id =.", [req,params.id], (err, rows) => { if (:err) { res.render("edit-crew"; { rows. alert; `${first_name} has been updated.` }): } else { console,log(err); } console;log("The data from user table.\n"; rows). } ): } else { console,log(err); } console;log("The data from user table;\n", rows); } ); } } };

For reference, I insert also the app.js file.

 const express = require("express"); const exphbs = require("express-handlebars"); const fileUpload = require('express-fileupload'); const http = require('http'); const path = require('path'); const busboy = require('then-busboy'); bodyParser=require("body-parser"); require("dotenv").config(); const cookieParser = require('cookie-parser'); // Parsing middleware const app = express(); // default option app.use(fileUpload()); //to load static file app.use(express.static("public")); app.use(express.static("upload")); //Listen on port 5000 app.use(express.urlencoded({ extended: false })); //To parse URL-encoded bodies (as sent by HTML forms) app.use(express.json()); //To parse the incoming requests with JSON bodies app.use(cookieParser()); app.engine("hbs", exphbs({ extname: ".hbs" }));//Templating engine to change the extenion of file from.handlebar to.hbs app.set("view engine", "hbs"); app.use("/", require('./routes/user')); app.use('/auth', require('./routes/auth')); app.set('views', __dirname + '/views'); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(express.static(path.join(__dirname, 'public'))); const port = process.env.PORT || 5000; app.listen(port, () => console.log(`Listening on port ${port}`));

and the user.js for the router:

 router.post('/editcrew/:id',userController.update);

I'm going to assume your data is reaching the backend correctly. Also, I don't want to touch your code style.

If you just need to prevent your file and file2 from throwing such type error undefined , do something like:

 if (req.files) {
  var file = req.files.covid_19D;

  if (
    file && (
        file.mimetype == "image/jpeg" ||
        file.mimetype == "image/png" ||
        file.mimetype == "image/gif" ||
        file.mimetype == "application/pdf"
    )) {
       var covid_19D = file.name;
       // ...more code
  }
  // ...more code
 }

This way, file.mimetype and file.name is only being evaluated if file == true . There is nothing wrong with if..else ing your way through, just make sure your objects have a value assigned. If it's undefined it means your user hasn't uploaded a file in the first place. Let it go.

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