项目中经常会遇到上传图片和头像 记录下接口
- 上传头像
逻辑:每个账号都只有一个头像 所以这里将每个账号的头像名称设为固定值,如User_(userid).jpg 这样 只需要上传此名称的图片 前天根据id获取就行
@ApiOperation(value = "上传用户头像",httpMethod = "POST", produces = "application/json")
@ApiResponse(code = 200, message = "success", response = ResponseBase.class)
@RequestMapping(value = "/uploadPortrait",method = RequestMethod.POST, produces = "application/json")
public ResponseBase uploadPortrait(@RequestParam("file") MultipartFile file,HttpServletRequest request){
String userid = request.getParameter("userid");
File dir = new File(UPLOADED_File);
if(!dir.exists()){
dir.mkdir();
}
String fileName = "User_"+userid;
String originalFilename = file.getOriginalFilename();
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
String targetUploadPath = dir + File.separator + fileName + suffix;
File imgurl = new File(targetUploadPath);
if(imgurl.exists()){
FileUtils.deleteQuietly(imgurl);
}
try {
FileUtils.writeByteArrayToFile(new File(targetUploadPath), file.getBytes());
return setResultSuccess();
} catch (IOException e) {
System.out.println(e.getStackTrace());
}
return setResultError("头像上传失败");
}
2.文件上传 多图上传
逻辑 多张图片上传 图片名起初为uuid-test 当用户点击保存时 删除-test后缀 关联图片 这样要是发生异常情况 写个定时器 定期清理 -test后缀 冗余图片 可以大大减少垃圾图片
//处理文件上传
@ApiOperation(value = "上传图片文件,支持多图片上传")
@RequestMapping(value="/uploadImgs", method = RequestMethod.POST, produces = "application/json")
public JSONArray uploadImgs(@ApiParam(name = "file", required = true, value = "file") @RequestParam("file") MultipartFile[] files){
JSONArray res = new JSONArray();
File flie = new File(UPLOADED_File);
if(flie.exists()) {
flie.mkdir();
}
for (int i = 0; i < files.length; i++) {
MultipartFile file = files[i];
String originalFilename = file.getOriginalFilename();
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
String filename = UUID.randomUUID().toString().replaceAll("-", "") + "-test" + suffix;
String targetUploadPath = flie + File.separator + filename;
try {
FileUtils.writeByteArrayToFile(new File(targetUploadPath), file.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
res.add(filename);
}
return res;
}
3.获取图片
前端img url直接访问后端/getImages/图片名 即可显示图片
@ApiOperation(value = "获取图片", httpMethod = "GET", produces = "application/json")
@ApiResponse(code = 200, message = "success", response = ResponseBase.class)
@RequestMapping(value = "/getImages/{filename}", method = RequestMethod.GET, produces = "application/json")
public void getImages(HttpServletResponse response, @PathVariable("filename") String filename) throws IOException {
String path = UPLOADED_File + filename;
File dir = new File(path);
if(dir.exists()){
byte[] bytes = FileUtils.readFileToByteArray(dir);
OutputStream out = response.getOutputStream();
out.write(bytes);
out.flush();
out.close();
}
}
网友评论