简体   繁体   English

如何从 MySql / Node.js 服务器动态检索文件?

[英]How can I dynamically retrieve files from MySql / Node.js server?

I'm working on my CRUD app what I`m trying to do is to download files from MySql Nodejs server.我正在开发我的 CRUD 应用程序,我想做的是从 MySql Nodejs 服务器下载文件。 Here the steps I've achieved so far:到目前为止,我已经实现了以下步骤:

  • I create the below function to query MySql database to find the id=179 (just a random id).我创建了下面的 function 来查询 MySql 数据库以找到id=179 (只是一个随机 id)。 The function is inside a file called userContoller.js. function 位于名为 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); }); }

With Handlebars in another file called index.hbs I fetch the file with {{this.profile_image}}在另一个名为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}}

In another file user.js I placed the router for the /index page.在另一个文件user.js ,我为/index页面放置了路由器。

 router.get('/index', userController.readfile);

All work fine.一切正常。 What I want to do is to dynamically access the user id, instead of me inserting 'SELECT * FROM user WHERE id="179"' .我想要做的是动态访问用户 ID,而不是我插入'SELECT * FROM user WHERE id="179"' To achieve this I create the following function exports.viewall (also included in userController.js ).为了实现这一点,我创建了以下 function exports.viewall (也包含在userController.js中)。 exports.viewall function download the correct name of the file but instead to download the *.jpeg version download a USELESS *.html version and same with other type of file like *.pdf. exports.viewall function 下载正确的文件名,而不是下载 *.jpeg 版本 下载无用的 *.html 版本,与其他类型的文件相同,如 *.Z437175BA4191210EE094Z.19

 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); }); }

How can I dynamically properly query the MySql/Nodejs server to download the file to my local machine?如何动态正确查询 MySql/Nodejs 服务器以将文件下载到本地计算机?

for reference below I put the app.js:作为参考,我把 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}`));

You can use express dynamic routes.您可以使用快速动态路由。 And pass a string variable for querying the sql database.并传递一个字符串变量用于查询 sql 数据库。 like this像这样

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);
    }
  });
});

I re-think the whole problem and here is the solution working for me:我重新考虑了整个问题,这是对我有用的解决方案:

1- On my front-end side I simply add ../upload/ in front of my handlebar link to database as per below code: 1-在我的前端,我只需按照以下代码在我的车把链接前面添加../upload/到数据库:

<a href="../upload/{{this.profile_image}}">DOWNLOAD</a>

In this way I re-route the the link to the folder where I keep all the file on my server.通过这种方式,我将链接重新路由到将所有文件保存在服务器上的文件夹。

2- I left the router unchanged, so dinamycally get the id with the /:id on client side request 2-我让路由器保持不变,所以在客户端请求中以/:id动态获取 id

router.get('/viewcrew/:id',userController.viewall);

3- I left the controller unchanged as well as follow: 3- 我将 controller 保持不变,如下所示:

 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); }); }

In this way, I create a download point as per front end code which downloads any file from the server taking the name reference from the MySql database:)这样,我根据前端代码创建了一个下载点,该代码从服务器下载任何文件,名称参考来自 MySql 数据库:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM