Spring中上传文件处理详细说明

  1. 请求:必须是POST请求
  2. 表单:enctype="multipart/form-data"
    <form class="mt-5" method="post" enctype="multipart/form-data" th:action="@{/user/upload}">
    					<div class="form-group row mt-4">
    						<label for="head-image" class="col-sm-2 col-form-label text-right">选择头像:</label>
    						<div class="col-sm-10">
    							<div class="custom-file">
    								<input type="file" name="headerImage" th:class="|custom-file-input ${error!=null?'is-invalid':''}|" id="head-image" lang="es" required="">
    								<label class="custom-file-label" for="head-image" data-browse="文件">选择一张图片</label>
    							</div>
    							<div class="invalid-feedback" th:text="${error}">
    								显示错误信息
    							</div>
    						</div>
    					</div>
    					<div class="form-group row mt-4">
    						<div class="col-sm-2"></div>
    						<div class="col-sm-10 text-center">
    							<button type="submit" class="btn btn-info text-white form-control">立即上传</button>
    						</div>
    					</div>
    				</form>

  3. SpringMVC:通过MultipartFile处理上传文件
        private static final Logger logger = LoggerFactory.getLogger(UserController.class);
        @Value("${community.path.upload}")
        private String updatePath;
        @Value("${community.path.domain}")
        private String domain;
        @Value("${server.servlet.context-path}")
        private String contextPath;
        @Autowired
        private UserService userService;
        @Autowired
      private HostHoler hostHoler;
    @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 file = new File(updatePath + "/" + fileName);
             try {
                 //存储文件
                 headerImage.transferTo(file);//将图片信息直接存入该文件中
             } catch (IOException e) {
                 logger.error("上传文件失败"+e.getMessage());
                 throw  new RuntimeException("上传文件失败,服务器发送异常");
             }
             //更新当前用户头像路径(web访问路径)
             //http://localhost:8080/community/user/header/xxx.png
             User user = hostHoler.getUser();
             String headerUrl=domain+contextPath+"/user/header/"+fileName;
             userService.updateHeader(user.getId(),headerUrl);
               return "redirect:/index";
         }
         @RequestMapping(path = "/header/{fileName}",method = RequestMethod.GET)
        public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response){
          //服务器存放路径
             fileName=updatePath+"/"+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());
                }
         }

    注意:还需要在application.properties中配置好图片在硬盘的位置

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大磊程序员(“hello world”)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值