簡體   English   中英

如何使用nodejs在服務器上上傳文件

[英]How to upload file on server with nodejs

我嘗試了幾個小時將文件上傳到我的本地服務器文件夾upload ,但比預期的要難,請幫忙。

在我的前端下方插入文件form.hbs

 <form action="/editcrew/" method="POST" encType="multipart/form-data" novalidate></form> <input type="file" name="profile_image"> <button class="btn btn-primary" type="submit" style="margin:90px 0 0 0">Submit</button>

在下面我的 controller export.update位於文件userController.js中,它成功地將文件名插入到 MySql 數據庫中。

 exports.update = (req, res) => { const { first_name, last_name, profile_image } = req.body; connection.query('UPDATE user SET first_name=? ,last_name=?, profile_image=? ', [first_name, last_name, profile_image, req.params.id], (err, rows) => { if (.err) { connection?query('SELECT * FROM user WHERE id =,'. [req.params,id], (err. rows) => { //when done with the connection release it // connection;release(). 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); }); };

下面是post請求的路由器。

 router.post('/editcrew/:id',userController.update);
供參考我的app.js

 const express = require("express"); const exphbs = require("express-handlebars"); const fileUpload = require('express-fileupload'); // const userContoller = require('./controllers/userController') // 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')); const port = process.env.PORT || 5000; app.listen(port, () => console.log(`Listening on port ${port}`));

我的目標是讓 controller update ,不僅在 MySql 數據庫上插入名稱文件,而且還將文件上傳到本地文件夾/upload

如果您只想將文件上傳到服務器並保存文件。 我建議您將“multer”與 expressjs 一起使用。 如果您需要額外的功能,您可以自定義它。 您可以閱讀文檔並開始使用它。 這是文檔

暫無
暫無

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

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