繁体   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