写一个页面实现一个按钮选择需要上传的文件,上传到服务器,使用nginx 配置代理访问此页面
时间: 2023-11-27 12:52:14 浏览: 73
好的,您可以参考以下代码实现:
HTML代码:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传示例</title>
</head>
<body>
<h1>文件上传示例</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<br>
<br>
<input type="submit" value="上传文件">
</form>
</body>
</html>
```
其中,`enctype="multipart/form-data"`是指表单中含有文件上传的内容;`action="/upload"`是指将表单提交到服务器的`/upload`接口。
接下来,我们需要在服务器端使用`nginx`进行代理配置,实现文件上传的功能。
nginx配置文件:
```
http {
upstream nodejs {
server 127.0.0.1:3000;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://nodejs;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location /upload {
proxy_pass http://nodejs;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
client_max_body_size 50m;
}
}
}
```
对于`node.js`服务器,我们可以使用`express`框架来处理文件上传。后台代码的文件上传部分可参考以下代码:
server.js:
```
const express = require('express')
const multer = require('multer')
const app = express()
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
})
const upload = multer({ storage: storage })
app.use(express.static('public'))
app.post('/upload', upload.single('file'), function(req, res) {
console.log(req.file)
res.send('文件上传成功!')
})
app.listen(3000, function () {
console.log('服务器已启动,监听端口 3000...')
})
```
其中,`multer`是一个可以处理文件上传的中间件。
综上所述,我们就可以使用以上代码实现一个按钮选择需要上传的文件,上传到服务器,使用`nginx`配置代理访问此页面。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)