Element + WebServlet实现头像上传
后端解析到前端的请求 -> 存储到本地目录下 -> 将存储的路径返回给前端 -> 前端更新头像
后端代码:
@WebServlet(name = "FileUploadServlet", value = "/fileUpload.do")
public class FileUploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 文件上传是前端要求: 提交方式=post、enctype=multipart/form-data
String fileName = ""; //文件名
try {
// 1.验证请求方式、 enctype
if (ServletFileUpload.isMultipartContent(request)) {
// 获取项目存储路径 [项目的运行目录]
String realPath = getServletContext().getRealPath("/");
// 2.实例化ServletFileUpload对象
ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
// 3.解析request
Map<String, List<FileItem>> listMap = servletFileUpload.parseParameterMap(request);
listMap.forEach((key, value) -> {
System.out.println(key + "--" + value);
});
Set<String> keySet = listMap.keySet();
for (String key : keySet) {
List<FileItem> fileItems = listMap.get(key);
for (FileItem fileItem : fileItems) {
System.out.println("文件名:" + fileItem.getName());
System.out.println("是否是普通的表单元素:" + fileItem.isFormField());
System.out.println("长度:" + fileItem.getSize());
// 4.文件上传
if (!fileItem.isFormField()) { // 如果是一个文件上传组件
fileName = "img\\" + new Date().getTime() + fileItem.getName();
System.out.println(fileName);
// 新建空文件
File file = new File(realPath + "\\" + fileName);
System.out.println(realPath + fileName);
// 文件上传
fileItem.write(file);
}
}
}
}
} catch (FileUploadException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
}
ReturnEntity returnEntity = new ReturnEntity();
returnEntity.setCode(0);
returnEntity.setMessage(fileName);
ServletUtils.sendDataClient(response, returnEntity);
}
}
前端代码:
<template>
<div class="upload-avatar">
<el-upload
:action="uploadUrl"
:show-file-list="false"
:on-success="handleUploadSuccess"
:before-upload="beforeUpload"
:with-credentials="true"
>
<img class="avatar" :src="avatarUrl" :alt="defaultAvatar" />
<div class="tip">点击上传头像</div>
</el-upload>
</div>
</template>
<script>
export default {
data() {
return {
defaultAvatar: '默认头像',
avatarUrl: 'https://lk.zinzin.cc/i/64b4f9c128d1b.png', // 头像url
uploadUrl: 'http://192.168.3.177:8088/javasm_war_exploded/fileUpload.do' // 上传地址
}
},
methods: {
// 上传前的校验
beforeUpload(file) {
const isJPG = file.type === 'image/jpeg'
const isPNG = file.type === 'image/png'
const isLt2M = file.size / 1024 / 1024 < 2
if (!isJPG && !isPNG) {
this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
return false
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!')
return false
}
return true
},
// 上传成功的回调函数
handleUploadSuccess(res) {
if (res.code === 0) {
this.$message.success('上传头像成功!')
console.log(res.message)
this.avatarUrl =
'http://192.168.3.177:8088/javasm_war_exploded/' + res.message
} else {
this.$message.error('上传头像失败!')
}
}
}
}
</script>
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409eff;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
评论区