【发布时间】:2022-01-04 14:48:16
【问题描述】:
我正在开发我的 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);
一切正常。我想要做的是动态访问用户ID,而不是我插入'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}`));
【问题讨论】:
标签: javascript mysql node.js express handlebars.js