如何从 MySql / Node.js 服务器动态检索文件?
How can I dynamically retrieve files from MySql / Node.js server?
我正在开发我的 CRUD 应用程序,我想做的是从 MySql Nodejs 服务器下载文件。这是我到目前为止所完成的步骤:
- 我创建了以下函数来查询 MySql 数据库以查找
id=179
(只是一个随机 ID)。该函数位于名为 userContoller.js. 的文件中
exports.readfile = (req, res) => {
connection.query('SELECT * FROM user WHERE id="179"', (err, rows) => {
if (!err) {
res.render('index', { rows, layout: 'main3' });
} else {
console.log(err);
}
console.log('The data from user table:\n', rows);
});
}
在另一个名为 index.hbs
的文件中使用 Handlebars 我使用 {{this.profile_image}}
获取文件
{{#each rows}}
{{#if this.profile_image}}
<a href="{{this.profile_image}}" download>
<img class="card__image" src="{{this.profile_image}}" loading="lazy" alt="User Profile">
{{else}}
<img class="card__image" src="/img/cert.png" loading="lazy" alt="User Profile">
</a>
{{/if}}
在另一个文件 user.js
中,我为 /index
页面放置了路由器。
router.get('/index', userController.readfile);
一切正常。我想做的是动态访问用户标识,而不是我插入 'SELECT * FROM user WHERE id="179"'
。为此,我创建了以下函数 exports.viewall
(也包含在 userController.js
中)。 exports.viewall
函数下载文件的正确名称,而不是下载 *.jpeg 版本下载一个无用的 *.html 版本,与 *.pdf.
等其他类型的文件相同
exports.viewall = (req, res) => {
//User the connection
connection.query('SELECT * FROM user WHERE id=?', [req.params.id], (err, rows) => {
//when done with the connection, release it
if (!err) {
res.render('view-crew', { rows });
} else {
console.log(err);
}
// console.log('The data from user table:\n', rows);
});
}
如何动态正确地查询 MySql/Nodejs 服务器以将文件下载到我的本地计算机?
为了参考下面我把 app.js:
const express = require("express");
const path = require('path');
const exphbs = require("express-handlebars");
const fileUpload = require('express-fileupload');
const mysql = require('mysql');
// to be removed when deployed in heroku
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");
//link which tell to the server express.js to get the routeing from user.js
// const routes = require('./server/routes/user');
app.use("/", require('./routes/user'));
app.use('/auth', require('./routes/auth'));
// Connection Pool
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'nodejs-login'
});
app.post('', (req, res) => {
let sampleFile;
let uploadPath;
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send('No files were uploaded.');
}
// name of the input is sampleFile
sampleFile = req.files.sampleFile;
uploadPath = __dirname + '/upload/' + sampleFile.name;
console.log(sampleFile);
// Use mv() to place file on the server
sampleFile.mv(uploadPath, function (err) {
if (err) return res.status(500).send(err);
connection.query('UPDATE user SET profile_image = ? WHERE id="179"', [sampleFile.name], (err, rows) => {
if (!err) {
res.redirect('/index');
} else {
console.log(err);
}
});
});
});
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on port ${port}`));
您可以使用快速动态路由。并传递一个字符串变量用于查询 sql 数据库。像这样
app.post('/:id', (req, res) =>{
const id = req.params.id.toString;
const queryString = `UPDATE user SET profile_image = ? WHERE id=${id}`
connection.query( queryString,
[sampleFile.name], (err, rows) => {
if (!err) {
res.redirect('/index');
} else {
console.log(err);
}
});
});
我重新考虑了整个问题,这是对我有用的解决方案:
1- 在我的前端,我只需按照以下代码将车把 link 前面的 ../upload/
添加到数据库中:
<a href="../upload/{{this.profile_image}}">DOWNLOAD</a>
通过这种方式,我将 link 重新路由到我在服务器上保存所有文件的文件夹。
2- 我修改了路由器,所以在客户端请求
时动态获取带有 /:pic
的图片
router.get('/upload/:pic', function (req, res) {
var file = __dirname + '/../upload/' + req.params.pic;
res.download(file);
});
3- 我离开控制器如下:
exports.viewall = (req, res) => {
connection.query('SELECT * FROM user WHERE id=?', [req.params.id], (err, rows) => {
if (!err) {
res.render('view-crew', { rows });
} else {
console.log(err);
}
// console.log('The data from user table:\n', rows);
});
}
这样,我根据前端代码创建了一个下载点,它从服务器下载任何文件,并从 MySql 数据库获取名称引用:)
我正在开发我的 CRUD 应用程序,我想做的是从 MySql Nodejs 服务器下载文件。这是我到目前为止所完成的步骤:
- 我创建了以下函数来查询 MySql 数据库以查找
id=179
(只是一个随机 ID)。该函数位于名为 userContoller.js. 的文件中
exports.readfile = (req, res) => {
connection.query('SELECT * FROM user WHERE id="179"', (err, rows) => {
if (!err) {
res.render('index', { rows, layout: 'main3' });
} else {
console.log(err);
}
console.log('The data from user table:\n', rows);
});
}
在另一个名为 index.hbs
的文件中使用 Handlebars 我使用 {{this.profile_image}}
{{#each rows}}
{{#if this.profile_image}}
<a href="{{this.profile_image}}" download>
<img class="card__image" src="{{this.profile_image}}" loading="lazy" alt="User Profile">
{{else}}
<img class="card__image" src="/img/cert.png" loading="lazy" alt="User Profile">
</a>
{{/if}}
在另一个文件 user.js
中,我为 /index
页面放置了路由器。
router.get('/index', userController.readfile);
一切正常。我想做的是动态访问用户标识,而不是我插入 'SELECT * FROM user WHERE id="179"'
。为此,我创建了以下函数 exports.viewall
(也包含在 userController.js
中)。 exports.viewall
函数下载文件的正确名称,而不是下载 *.jpeg 版本下载一个无用的 *.html 版本,与 *.pdf.
exports.viewall = (req, res) => {
//User the connection
connection.query('SELECT * FROM user WHERE id=?', [req.params.id], (err, rows) => {
//when done with the connection, release it
if (!err) {
res.render('view-crew', { rows });
} else {
console.log(err);
}
// console.log('The data from user table:\n', rows);
});
}
如何动态正确地查询 MySql/Nodejs 服务器以将文件下载到我的本地计算机?
为了参考下面我把 app.js:
const express = require("express");
const path = require('path');
const exphbs = require("express-handlebars");
const fileUpload = require('express-fileupload');
const mysql = require('mysql');
// to be removed when deployed in heroku
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");
//link which tell to the server express.js to get the routeing from user.js
// const routes = require('./server/routes/user');
app.use("/", require('./routes/user'));
app.use('/auth', require('./routes/auth'));
// Connection Pool
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'nodejs-login'
});
app.post('', (req, res) => {
let sampleFile;
let uploadPath;
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send('No files were uploaded.');
}
// name of the input is sampleFile
sampleFile = req.files.sampleFile;
uploadPath = __dirname + '/upload/' + sampleFile.name;
console.log(sampleFile);
// Use mv() to place file on the server
sampleFile.mv(uploadPath, function (err) {
if (err) return res.status(500).send(err);
connection.query('UPDATE user SET profile_image = ? WHERE id="179"', [sampleFile.name], (err, rows) => {
if (!err) {
res.redirect('/index');
} else {
console.log(err);
}
});
});
});
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on port ${port}`));
您可以使用快速动态路由。并传递一个字符串变量用于查询 sql 数据库。像这样
app.post('/:id', (req, res) =>{
const id = req.params.id.toString;
const queryString = `UPDATE user SET profile_image = ? WHERE id=${id}`
connection.query( queryString,
[sampleFile.name], (err, rows) => {
if (!err) {
res.redirect('/index');
} else {
console.log(err);
}
});
});
我重新考虑了整个问题,这是对我有用的解决方案:
1- 在我的前端,我只需按照以下代码将车把 link 前面的 ../upload/
添加到数据库中:
<a href="../upload/{{this.profile_image}}">DOWNLOAD</a>
通过这种方式,我将 link 重新路由到我在服务器上保存所有文件的文件夹。
2- 我修改了路由器,所以在客户端请求
时动态获取带有/:pic
的图片
router.get('/upload/:pic', function (req, res) {
var file = __dirname + '/../upload/' + req.params.pic;
res.download(file);
});
3- 我离开控制器如下:
exports.viewall = (req, res) => {
connection.query('SELECT * FROM user WHERE id=?', [req.params.id], (err, rows) => {
if (!err) {
res.render('view-crew', { rows });
} else {
console.log(err);
}
// console.log('The data from user table:\n', rows);
});
}
这样,我根据前端代码创建了一个下载点,它从服务器下载任何文件,并从 MySql 数据库获取名称引用:)