前后端服务器分离时,前端如何上传图片到前端服务器?-灵析社区

我想对你说

### 前端如何把图片上传到服务端? #### 使用技术:vue2 + elementUI #### 背景: 前端和后端分别部署到不同的服务器上,前端页面是个表单, 表单里面有上传图片的功能,上传的图片然后在其他页面展示的业务逻辑。后台提供的表单接口要求我只把图片名字(xxxx.png/xxx.jpg)传给他。 ![image.png](https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20241008/ff360fcf3c2065e39e94c313327bfb71.png) #### 问题: 我把生产包放到nginx里的html文件夹后测试。发现没法上传。nginx的配置也做过修改了 vue: data() { return { imageUrl: '', action: window.NODE_ENV === 'development' ? '' : window.location.origin + '/common/image/' } }, methods: { handleChange(file) { console.log('file', file); this.imageUrl = URL.createObjectURL(file.raw) } handleAvatarSuccess(res, file) { // console.log('res',res) // console.log(file) }, beforeAvatarUpload(file) { }, } nginx配置 server { listen 8085; server_name 10.19.129.12:19090; # 127.0.0.1 #10.19.129.12:19090 charset utf-8; access_log on; add_header Access-Control-Allow-Origin '*'; add_header Access-Control-Allow-Methods 'POST,PUT,GET,DELETE'; add_header Access-Control-Allow-Headers 'version, access-token, user-token, Accept, apiAuth, User-Agent, Keep-Alive, Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With'; # 前端vue转发 或者是/dist/ location /dist/ { root html; rewrite /(.*)$ /$1 break; index login.html index.html index.htm; #启动文件 } location /common/image/ { root D:/codes/nginx-1.18.0/; index index.html index.htm; } } #### 结果: 生产环境下上传图片报错了:![image.png](https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20241008/7d283f08814c084ffce2d324c6d625dd.png)![image.png](https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20241008/62d13f4ee2f849d6834d56c981442148.png) #### 目录: ![image.png](https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20241008/a1db502b72dd1daeb17bcac8053790c4.png)![image.png](https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20241008/d18d756e82d7cf3e86499aef941e302c.png)![image.png](https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20241008/5266acd315c481091ea9b22e24cb467d.png) 尝试1:传给后台的图片名字是base64,展示的时候后台再返回base64,但是加载太慢没有通过验收 尝试2:我手动把图片复制到'/common/image/'文件夹下,展示的时候是可以展示的。 img可以展示: data() { return { // coverPhotoName是后台返回的图片名字 imgSrc: window.location.origin + '/common/image/' + coverPhotoName } } #### 请问我应该怎么修改代码才能做到把图片上传到'/common/image/'文件夹下?如果我提供的信息太少可以积极指正,谢谢各位大佬🥰

阅读量:191

点赞量:0

问AI
给你提供个大概得思路 1.先要准备一个后台上传服务。用java、node等等都可以实现。 你这里提到了纯前端,我以node为例子,假设你的文件要保存到服务器的"/home/uploads"目录下 const http = require('http'); const fs = require('fs'); const path = require('path'); const formidable = require('formidable'); const server = http.createServer((req, res) => { if (req.method === 'POST' && req.url === '/upload') { const form = new formidable.IncomingForm(); form.parse(req, (err, fields, files) => { if (err) { console.error('文件解析失败:', err); res.writeHead(500, {'Content-Type': 'text/plain'}); res.end('文件解析失败'); return; } const uploadDir = './uploads'; if (!fs.existsSync(uploadDir)) { fs.mkdirSync(uploadDir); } const fileName = fields.fileName; // 获取前端传递过来的文件名 const filePath = path.join(uploadDir, fileName); // 使用前端传递的文件名 const writeStream = fs.createWriteStream(filePath); fs.createReadStream(files.file.path).pipe(writeStream); writeStream.on('close', () => { console.log('文件上传成功:', filePath); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('文件上传成功'); }); }); } else { res.writeHead(404, {'Content-Type': 'text/plain'}); res.end('Not Found'); } }); const PORT = 3000; server.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); }); 2.配置nginx的转发。 转发上传接口、配置静态文件访问 #转发上传接口 location /upload { proxy_pass http://localhost:3000/upload; } #配置静态文件访问 location /oss/ { alias /home/upload/; autoindex on; # 打开目录浏览功能,可选 } 3.前端axios上传 const formData = new FormData(); formData.append('file', file); axios.post('/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' }, params: { fileName: fileName // 将文件名作为请求参数传递给后端 } }) 4.你的文件地址就是你的nginx的domain+/oss/你的上传的文件名 *** 我只是给你大概列个思路,具体代码你可以gpt或者网上找示例