仿牛客网社区项目(九)账号设置
作者:互联网
上传文件
- 上传文件
- 请求:必须是POST请求
- 表单:enctype=“multipart/form-data”
- Spring MVC:通过 MultipartFile 处理上传文件
- 开发步骤
- 访问账号设置页面
- 上传头像
- 获取头像
开发步骤
①访问账号设置页面
前端部分,已写好.html文件
②上传头像
MultipartFile 用于接受前端传回的图片
@RequestMapping(path = "/upload",method = RequestMethod.POST)
public String uploadHeader(MultipartFile headerImage, Model model){
if(headerImage == null){
model.addAttribute("error","您还没有选择图片!");
return "/site/setting";
}
String fileName = headerImage.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf("."));
if(StringUtils.isBlank(suffix)){
model.addAttribute("error","文件格式不正确");
return "/site/setting";
}
//生成随机文件名
fileName = CommunityUtil.generateUUID() + suffix;
//确定文件的存放路径
File dest = new File(uploadPath + "/" +fileName);
try {
//存储文件
headerImage.transferTo(dest);
} catch (IOException e) {
logger.error("上传文件失败" + e.getMessage());
throw new RuntimeException("上传文件失败,服务器发生异常!",e);
}
//更新当前用户的头像的网址
User user = hostHolder.getUser();
String headerUrl = domain + contextPath +"/user/header/" + fileName;
userService.updateHeader(user.getId(),headerUrl);
return "redirect:/index";
}
程序当中用到了updateHeader()方法,以此需在服务层添加该方法
public int updateHeader(int userId,String headerUrl){
return userMapper.updateHeader(userId,headerUrl);
}
③获取头像
@RequestMapping(path = "/header/{fileName}",method = RequestMethod.GET)
public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response){
//服务器存放路径
fileName = uploadPath + "/" + fileName;
//文件后缀
String suffix = fileName.substring(fileName.lastIndexOf("."));
response.setContentType("image/" + suffix);
try (
FileInputStream fis = new FileInputStream(fileName);
OutputStream os = response.getOutputStream();
){
byte[] buffer = new byte[1024];
int b = 0;
while((b = fis.read(buffer)) != -1){
os.write(buffer,0, b);
}
} catch (IOException e) {
logger.error("读取头像失败" + e.getMessage());
}
}
④图片过大异常处理
Spirngboot默认最大上传10m,如果过大就会异常,前期用这个异常控制器处理,后期更新更好的方法
@ExceptionHandler(value = MultipartException.class)
@ResponseBody
public ModelAndView handleBusinessException(MaxUploadSizeExceededException ex) {
String msg;
if (ex.getCause().getCause() instanceof FileSizeLimitExceededException) {
log.error(ex.getMessage());
msg = "上传文件过大[单文件大小不得超过10M]";
} else if (ex.getCause().getCause() instanceof SizeLimitExceededException) {
log.error(ex.getMessage());
msg = "上传文件过大[总上传文件大小不得超过10M]";
} else {
msg = "上传文件失败";
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("/site/setting");
modelAndView.addObject("error","文件过大");
return modelAndView;
}
再配置好相关的.html文件即可进行测试
标签:文件,仿牛,String,账号,fileName,客网,error,return,上传 来源: https://www.cnblogs.com/nevererror/p/16210311.html