前后端服务器分离时,前端如何上传图片到前端服务器?
前端如何把图片上传到服务端?
使用技术:vue2 + elementUI
背景:
前端和后端分别部署到不同的服务器上,前端页面是个表单, 表单里面有上传图片的功能,上传的图片然后在其他页面展示的业务逻辑。后台提供的表单接口要求我只把图片名字(xxxx.png/xxx.jpg)传给他。
问题:
我把生产包放到nginx里的html文件夹后测试。发现没法上传。nginx的配置也做过修改了vue:
<el-upload
class="avatar-uploader"
:action="action"
accept="image/jpg,image/jpeg,image/png"
list-type="picture-card"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
:on-change="handleChange"
>
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
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;
}
}
结果:
生产环境下上传图片报错了:
目录:
尝试1:传给后台的图片名字是base64,展示的时候后台再返回base64,但是加载太慢没有通过验收尝试2:我手动把图片复制到'/common/image/'文件夹下,展示的时候是可以展示的。
img可以展示:
<img class="cardImg" :src="imgSrc">
data() {
return { // coverPhotoName是后台返回的图片名字
imgSrc: window.location.origin + '/common/image/' + coverPhotoName
}
}
请问我应该怎么修改代码才能做到把图片上传到'/common/image/'文件夹下?如果我提供的信息太少可以积极指正,谢谢各位大佬🥰
回复
1个回答

test
2024-06-20
给你提供个大概得思路
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或者网上找示例
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容