1. Vue页面<template>标签中添加elementUI组件
<el-row>
<el-col :span="20">
<!-- el-upload:上传组件
action:实现上传的servlet地址
show-file-list:是否显示上传成功的文件列表,boolean
on-success:钩子函数,文件上传成功之后调用,获取服务器上传成功之后设置文件名
before-upload:钩子函数,文件上传之前调用,验证文件的类型和大小
with-credentials:是否携带cookie,boolean -->
<el-form-item label="人员头像">
<el-upload class="avatar-uploader"
action="http://localhost:8090/FinancialSystem/fileUpload.do"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:with-credentials="true"
:before-upload="beforeAvatarUpload">
<img v-if="formData.customerHeadpic" :src="imgPath(formData.customerHeadpic)"
class="avatar" width="60px">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
</el-col>
</el-row>
2. Vue页面<script>标签中添加data定义和上传组件关联的函数
data(){
return{
formData: {
type: 'addAdmin',
customerName: '',
customerState: 1,
customerGrade: 1,
customerHeadpic: ''},
}
}
handleAvatarSuccess(res, file) {
console.log(res.message);
this.formData.customerHeadpic = res.message;
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
},
imgPath(adminImage) {
return "http://localhost:8090/FinancialSystem/" + adminImage;
},
}
3.后端FileUploadServlet接收前端发送的请求, 并将上传的图片存储到tomcat服务器
@WebServlet(name = "FileUploadServlet", value = "/fileUpload.do")
public class FileUploadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ReturnBean returnBean = new ReturnBean(33, "上传失败", null, null,null,null);
//请求对象的请求方式需要是post,并且enctype="multipatr/form-data"才能进行文件上传
if (ServletFileUpload.isMultipartContent(request)) {
try {
//实例化factory对象
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
//实例化上传servletFileUpload对象
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
//将request对象中的数据转为list
List<FileItem> fileItems = servletFileUpload.parseRequest(request);
if (fileItems != null) {
for (FileItem fileItem : fileItems) {
//如果fileItem不是普通的表单元素,就可以将该元素写到后端数据库
if (!fileItem.isFormField()) {
//获取项目存储的磁盘地址,到项目文件夹为止
String realPath = getServletContext().getRealPath("/");
//获取上传的文件的文件名
String name = fileItem.getName();
//新建的文件相对项目文件夹的存储路径(项目文件夹下的img文件夹)
String filePath = "img/" + new Date().getTime() + name;
//新建文件,提供文件的绝对路径参数
File file = new File(realPath + "/" + filePath);
//将上传的文件复制给新建的file文件,write方法会自动关闭流。这个write方法是diskfileItem中的方法,自带关闭功能
fileItem.write(file);
//文件在后端保存成功则输入文件保存成功提示码和文件存储的相对路径
returnBean.setCode(44);
returnBean.setMessage(filePath);
}
}
}
} catch (FileUploadException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
ServletUtil.dataChange(response,returnBean);
}
}
就可以做出这样上传图片的效果!