前台vue代码
<el-upload class="upload-demo" action="http://localhost:8080/Graduation_war_exploded/file/picture2"
:on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove"
:on-cxceed="handleExceed" :on-success="handleSuccess" :on-error="handleError" multiple :limit="3"
accept="image/jpeg,image/png" :file-list="fileList">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
data(){
return{
fileList: []
}
methods:{
handleSuccess() {
this.$message.success("图片上传成功")
},
handleError() {
this.$message.error("图片上传失败")
},
handleRemove(file, fileList) {
console.log(file, fileList);
},
handlePreview(file) {
console.log(file);
},
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
},
beforeRemove(file, fileList) {
return this.$confirm(`确定移除 ${ file.name }?`);
}
}
后台java代码
@PostMapping(value = "picture2")
@ResponseBody
public Response uploadFile2(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
System.out.println("执行upload,执行图片上传");
System.out.println(file);
request.setCharacterEncoding("UTF-8");
// String user = request.getParameter("user");
if (!file.isEmpty()) {
System.out.println("成功获取照片");
String fileName = file.getOriginalFilename();
String path = null;
String type = null;
type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
System.out.println("图片初始名称为:" + fileName + " 类型为:" + type);
if (type != null) {
if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) {
// 项目在容器中实际发布运行的根路径
// String SavefilePath = "D:/images/";
// 自定义的文件名称
String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;
// 设置存放图片文件的路径
path = SavefilePath + trueFileName;
System.out.println("存放图片文件的路径:" + path);
file.transferTo(new File(path));
System.out.println("文件成功上传到指定目录下");
return new Response(200, true, "上传文件成功", trueFileName);
} else {
System.out.println("不是我们想要的文件类型,请按要求重新上传");
return new Response(201, false, "不是我们想要的文件类型,请按要求重新上传", null);
}
} else {
System.out.println("文件类型为空");
return new Response(201, false, "文件类型为空", null);
}
} else {
System.out.println("没有找到相对应的文件");
return new Response(201, false, "没有找到相对应的文件", null);
}
}