1.controller.java的编写(以自己的项目为例)
/* * 图片上传 * */ @PostMapping("/uploadPhoto") public HashMap
uploadPhoto(@RequestParam MultipartFile file, HttpServletRequest request) throws IOException { HashMap map = new HashMap<>(); File path=new File(ClassUtils.getDefaultClassLoader().getResource("static").getPath()); File upload=new File(path.getAbsolutePath(),"upload1");//static/upload1为上传地址 if (!upload.exists()) { upload.mkdir(); } //创建路径 // String path = request.getServletContext().getRealPath("/upload"); // File f = new File(path); // if (!f.exists()) { // f.mkdir(); // } // String path = "D:\\code\\src\\main\\resources\\static\\images\\";自己写的死地址 String oldFilename = file.getOriginalFilename(); String newFilename = UUID.randomUUID().toString() + oldFilename.substring(oldFilename.lastIndexOf(".")); // String filepath = path + "/" + newFilename; String filepath=upload.getAbsolutePath()+"\\"+newFilename; file.transferTo(new File(filepath)); map.put("code", 200); map.put("oldFileName", oldFilename); map.put("newFileName","/upload1/"+newFilename); map.put("fileSize", file.getSize()); System.out.println("oldFilename: " + oldFilename); System.out.println("newFilename: " + newFilename); System.out.println("上传的路径: " + path); return map; } @PostMapping("/addUser") public HashMap addUser(@RequestBody User u) { HashMap map = new HashMap<>(); u.setCreateTime(new Timestamp(new java.util.Date().getTime())); int n = userService.addUser(u); if (n > 0) { map.put("code", 200); map.put("msg", "添加成功"); } else { map.put("code", 401); map.put("msg", "添加失败"); } return map; }
2.vue组建的编写。
action里面就是要上传调用的接口。
下面是头像上传成功的回调函数和图片限制函数
// 头像上传
handleAvatarSuccess(res, file) { //res表示服务器返回的json对象,file表示上传的文件
// this.ruleForm.photo = URL.createObjectURL(file.raw);
this.ruleForm.photo = res.newFileName, //为添加用户做准备
console.log("返回的结果:" + res.newFileName);
this.imgUrls = "http://localhost:9090/images/" + res.newFilename; //服务器返回的新文件名
},
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;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)