簡體   English   中英

如何從 MySql / Node.js 服務器動態檢索文件?

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

我正在開發我的 CRUD 應用程序,我想做的是從 MySql Nodejs 服務器下載文件。 到目前為止,我已經實現了以下步驟:

  • 我創建了下面的 function 來查詢 MySql 數據庫以找到id=179 (只是一個隨機 id)。 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); }); }

在另一個名為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"' 為了實現這一點,我創建了以下 function exports.viewall (也包含在userController.js中)。 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); }); }

如何動態正確查詢 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-在我的前端,我只需按照以下代碼在我的車把鏈接前面添加../upload/到數據庫:

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

通過這種方式,我將鏈接重新路由到將所有文件保存在服務器上的文件夾。

2-我讓路由器保持不變,所以在客戶端請求中以/:id動態獲取 id

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

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

這樣,我根據前端代碼創建了一個下載點,該代碼從服務器下載任何文件,名稱參考來自 MySql 數據庫:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM