如果前端文件字段为空,如何不覆盖 MySql 列
How to don't overwrite the MySql column if the front end file field is empty
我正在使用下面的控制器 exports.update
在我的 CRUD 应用程序上上传数据和文件。我有一个大问题,我需要 help/advice.
在客户端,如果上传文件字段,例如covid_19D
保持为空但其他值已填充并提交 post 请求,文件空字段覆盖 covid_19D
MySql 数据库列,删除先前输入的文件名并保留 covid_19D
MySql 列值为空。
我该如何解决这个问题?如果在客户端提交 post 请求并且文件字段为空,是否不覆盖之前在 MySql 列加载的文件名?
这是我的前端:
crew-forms.hbs
<div class="row">
{{!-- covid-19 vaccination --}}
<div class="col-md-6 mt-5">
<br>
<input class="form-control" type="text" placeholder="COVID-19 VACCINATION CERTIFICATES" aria-label="readonly input example" readonly data-bs-trigger="focus" role="button" data-bs-toggle="popover" title="Covid-19 vaccination certificate.">
</div>
<div class="col-md-6 mt-5">
<br>
<input type="text" id="datepickercovid_19" value="{{this.covid_19}}" placeholder="iss. date (mm/dd/yyyy)" name='covid_19'>
</div>
{{!-- input file covid_19 --}}
<div class="col-md-6">
<br>
<input type="file" name="covid_19D" multiple id="file_box" value="{{this.covid_19D}}" />
并编辑-crew.hbs
{{#each rows}}
<form class="row g-1 needs-validation" method="POST" action="/editcrew/{{this.id}}" encType="multipart/form-data" novalidate>
{{> crew-form}}
</form>
{{/each}}
这里是userController.js
exports.update = async(req, res) => {
try {
await upload(req, res);
// --FILE HANDLING BLOCKCODE---
var find = JSON.parse(JSON.stringify(req.files)); // to remove Object:null prototype
// conditional statments to hanlde the front end file existence.
if (find.hasOwnProperty('covid_19D') == false) {
var covid_19D = ""
} else {
var covid_19D = find.covid_19D[0].filename
}
if (find.hasOwnProperty('fitnessD') == false) {
var fitnessD = ""
} else {
var fitnessD = find.fitnessD[0].filename
}
} 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}`);
}
// ---DATA ENTERING BLOCK CODE---
var post = req.body;
var first_name = post.first_name;
var last_name = post.last_name;
var email = post.email;
var phone = post.phone;
var coc = post.coc;
var expiration = post.expiration;
var covid_19 = post.covid_19;
var fitness = post.fitness;
var yellowF = post.yellowF;
connection.query('UPDATE user SET first_name=? ,last_name=?, email=?, phone=?, coc=?, expiration=?, covid_19=?,covid_19D=? , fitness=? ,fitnessD=? WHERE id = ?', [first_name, last_name, email, phone, coc, expiration, covid_19, covid_19D, fitness, 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);
});
}
这是我的 app.js
const express = require("express");
const exphbs = require("express-handlebars");
const path = require('path');
bodyParser = require("body-parser");
// to be removed when deployed in heroku
require("dotenv").config();
const cookieParser = require('cookie-parser');
// Parsing middleware
const app = express();
//to load static file
app.use(express.static("public"));
// app.use(express.static("upload"));
//Listen on port 5000
app.use(express.urlencoded({
extended: true
})); //To parse URL-encoded bodies (as sent by HTML forms) set from false to true as per bezkoder tutorial
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}`));
在此先感谢您对正确路径的任何重定向建议!
好的,我明白了!
我简单的从前端的数据库中调出存储的文件名,用req.body.covid_19D到post变量名
这里是代码片段:
try {
await upload(req, res);
// --FILE HANDLING BLOCKCODE---
var find = JSON.parse(JSON.stringify(req.files));// to remove Object:null prototype
// conditional statments to hanlde the front end file existence.
if (find.hasOwnProperty('covid_19D') == false) {
var covid_19D = req.body.covid_19D
} else {
var covid_19D = find.covid_19D[0].filename
}
我正在使用下面的控制器 exports.update
在我的 CRUD 应用程序上上传数据和文件。我有一个大问题,我需要 help/advice.
在客户端,如果上传文件字段,例如covid_19D
保持为空但其他值已填充并提交 post 请求,文件空字段覆盖 covid_19D
MySql 数据库列,删除先前输入的文件名并保留 covid_19D
MySql 列值为空。
我该如何解决这个问题?如果在客户端提交 post 请求并且文件字段为空,是否不覆盖之前在 MySql 列加载的文件名?
这是我的前端:
crew-forms.hbs
<div class="row">
{{!-- covid-19 vaccination --}}
<div class="col-md-6 mt-5">
<br>
<input class="form-control" type="text" placeholder="COVID-19 VACCINATION CERTIFICATES" aria-label="readonly input example" readonly data-bs-trigger="focus" role="button" data-bs-toggle="popover" title="Covid-19 vaccination certificate.">
</div>
<div class="col-md-6 mt-5">
<br>
<input type="text" id="datepickercovid_19" value="{{this.covid_19}}" placeholder="iss. date (mm/dd/yyyy)" name='covid_19'>
</div>
{{!-- input file covid_19 --}}
<div class="col-md-6">
<br>
<input type="file" name="covid_19D" multiple id="file_box" value="{{this.covid_19D}}" />
并编辑-crew.hbs
{{#each rows}}
<form class="row g-1 needs-validation" method="POST" action="/editcrew/{{this.id}}" encType="multipart/form-data" novalidate>
{{> crew-form}}
</form>
{{/each}}
这里是userController.js
exports.update = async(req, res) => {
try {
await upload(req, res);
// --FILE HANDLING BLOCKCODE---
var find = JSON.parse(JSON.stringify(req.files)); // to remove Object:null prototype
// conditional statments to hanlde the front end file existence.
if (find.hasOwnProperty('covid_19D') == false) {
var covid_19D = ""
} else {
var covid_19D = find.covid_19D[0].filename
}
if (find.hasOwnProperty('fitnessD') == false) {
var fitnessD = ""
} else {
var fitnessD = find.fitnessD[0].filename
}
} 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}`);
}
// ---DATA ENTERING BLOCK CODE---
var post = req.body;
var first_name = post.first_name;
var last_name = post.last_name;
var email = post.email;
var phone = post.phone;
var coc = post.coc;
var expiration = post.expiration;
var covid_19 = post.covid_19;
var fitness = post.fitness;
var yellowF = post.yellowF;
connection.query('UPDATE user SET first_name=? ,last_name=?, email=?, phone=?, coc=?, expiration=?, covid_19=?,covid_19D=? , fitness=? ,fitnessD=? WHERE id = ?', [first_name, last_name, email, phone, coc, expiration, covid_19, covid_19D, fitness, 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);
});
}
这是我的 app.js
const express = require("express");
const exphbs = require("express-handlebars");
const path = require('path');
bodyParser = require("body-parser");
// to be removed when deployed in heroku
require("dotenv").config();
const cookieParser = require('cookie-parser');
// Parsing middleware
const app = express();
//to load static file
app.use(express.static("public"));
// app.use(express.static("upload"));
//Listen on port 5000
app.use(express.urlencoded({
extended: true
})); //To parse URL-encoded bodies (as sent by HTML forms) set from false to true as per bezkoder tutorial
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}`));
在此先感谢您对正确路径的任何重定向建议!
好的,我明白了!
我简单的从前端的数据库中调出存储的文件名,用req.body.covid_19D到post变量名
这里是代码片段:
try {
await upload(req, res);
// --FILE HANDLING BLOCKCODE---
var find = JSON.parse(JSON.stringify(req.files));// to remove Object:null prototype
// conditional statments to hanlde the front end file existence.
if (find.hasOwnProperty('covid_19D') == false) {
var covid_19D = req.body.covid_19D
} else {
var covid_19D = find.covid_19D[0].filename
}