如何从不同的上传点在同一页面上上传多个文件。使用 nodejs express-fileupload
Posted
技术标签:
【中文标题】如何从不同的上传点在同一页面上上传多个文件。使用 nodejs express-fileupload【英文标题】:How to upload more than one file on the same page from different upload point. Using nodejs express-fileupload 【发布时间】:2022-01-17 00:06:43 【问题描述】:我在 *** 上环顾四周,但找不到适用于我的答案。几个小时以来我一直在努力寻找解决方案....
我有一个把手页面,用户可以在其中将他的文件上传到服务器和 mysql 数据库。对于使用express
file-upload
上传的一个文件,一切正常。
当我添加第二个上传点时,我将前端的字段留空,终端上没有要上传的文件,然后我提交发布请求,我收到以下错误:
TypeError: Cannot read property 'name' of undefined
我理解这是意料之中的,因为该字段为空并且对象 name
也保持为空,但是,我的应用程序的用户必须能够仅上传一个文件而不会出错。
我该怎么做才能让用户一次只上传一个文件而不会出错??
非常感谢任何正确路径的方向建议/解决方案!谢谢!
<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 file2 = req.files.fitnessD;
// console.log(profile_image)
if (
file && (file.mimetype == "image/jpeg" ||
file.mimetype == "image/png" ||
file.mimetype == "image/gif" ||
file.mimetype == "application/pdf"))
var covid_19D = file.name;
file.mv('./upload/' + file.name, function (err)
if (err)
return res.status(500).send(err);
else
file2 && (file2.mimetype == "image/jpeg" ||
file2.mimetype == "image/png" ||
file2.mimetype == "image/gif" ||
file2.mimetype == "application/pdf")
var fitnessD = file2.name;
file2.mv('./upload/' + file2.name, function (err)
if (err)
return res.status(500).send(err);
connection.query('UPDATE user SET first_name=? ,last_name=?, covid_19D=?,fitnessD=? WHERE id = ?', [first_name, last_name, covid_19D, fitnessD, 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);
);
);
;
);
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);
);
作为参考,我还插入了app.js
文件。
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`));
以及路由器的user.js
:
router.post('/editcrew/:id',userController.update);
【问题讨论】:
【参考方案1】:我将假设您的数据正确到达后端。另外,我不想碰你的代码风格。
如果您只需要防止您的file
和file2
抛出此类错误undefined
,请执行以下操作:
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
这样,file.mimetype
和 file.name
仅在 file == true
时被评估。
if..else
你的方式并没有错,只要确保你的对象有一个分配的值。如果它未定义,则意味着您的用户首先没有上传文件。放手吧。
【讨论】:
您好,我已将您的解决方案应用于代码。一个文件工作正常。我使用建议的代码编辑了上面的 export.update。我用 else 插入了file2
。当我尝试加载页面时,会出现以下错误。 TypeError: Cannot read property 'name' of undefined
引用这行代码`var FitnessD = file2.name;`。有什么建议吗??
尝试对 file2 应用与之前相同的验证以上是关于如何从不同的上传点在同一页面上上传多个文件。使用 nodejs express-fileupload的主要内容,如果未能解决你的问题,请参考以下文章