Upload files using MultipartFile

Posted by prasitc2005 on Fri, 31 Dec 2021 20:17:34 +0100

MultipartFile file upload

Today, we set up a avatar change setting, that is, first upload a picture file, and then modify the avatar path in the user object to the uploaded picture, ha!!!

  • The first step is to configure where these pictures are stored
  • You have to give him a path.
community.path.upload=e:/javaweb/work/data/upload
  • I put the file directly under the e disk, ha!

Then start the second step

  • Because it is only the modification of the avatar image, we do not need to write the data access layer
  • But we have a business of uploading avatars
  • So we write a method in userService
    // Upload Avatar
    public int updateHeader(int userId,String headerUrl){
        return userMapper.updateHeader(userId, headerUrl);
    }
  • The data access layer is written, and the user's Avatar saving path is modified through the user id
  • Then there is the preparation of the Controller, which is still very detailed
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public String uploadHeader(MultipartFile headerImage, Model model){
        if(headerImage == null){  // No pictures have been selected
            model.addAttribute("error","You haven't selected a picture yet!!!");
            return "/site/setting";
        }
        String fileName = headerImage.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if(StringUtils.isBlank(suffix)){
            model.addAttribute("error","The file format is incorrect!!!");
            return "/site/setting";
        }
        // Generate random picture names
        // http://localhost:8081/community/user/header/1.jpg
        fileName = CommunityUtil.generateUUID() + suffix;
        // Determine the storage path of the file
        File dest = new File(uploadPath + "/" + fileName);
        try {
            headerImage.transferTo(dest);
        } catch (IOException e) {
            logger.error("Long pass file failed" + e.getMessage());
            throw new RuntimeException("Failed to upload file, server exception!!", e);
        }
        // The path to update the current user's Avatar (web access path)
        User user = hostHolder.getUser();
        String headerUrl = domain + contextPath + "/user/header/" + fileName;
        userService.updateHeader(user.getId(),headerUrl);
        return "redirect:/index";
    }
  • The first is to set the path. Here we use MultipartFile to obtain the image file,
  • Note that this can only be used with a post request,
  • Then, there must be a name field in the input of the HTML layer, and the name must be consistent with the name of the MultipartFile object, otherwise the object will report a null pointer exception.
  • Then we first get the original file name and always get its extension to judge what kind of image it is.
  • If there is no extension, this is not a qualified picture. We can report an error and give feedback

  • Then we save the file. Through the above code, we can save the file to the file location we set at the beginning, and then write the obtained image file to the specified file through headerImage.
  • Then modify the user's Avatar path.

Response picture to browser

   @RequestMapping(value = "/header/{fileName}",method = RequestMethod.GET)
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response){
        // The path where the server is stored
        fileName = uploadPath + "/" + fileName;
        // file extension
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        // Response picture
        response.setContentType("image/" + suffix);
        try (
            OutputStream os = response.getOutputStream();
            FileInputStream fis = new FileInputStream(fileName);
        ){
            byte[] buffer = new byte[1024];
            int b=0;
            while((b = fis.read(buffer)) != -1){
                os.write(buffer,0,b);
            }
        } catch (IOException e) {
            logger.error("Failed to read Avatar:" + e.getMessage());
        }
    }
  • The response path we wrote here will be fixed, because the path of the response browser has been set as / user/header/{fileName} in the previously uploaded code
  • Then respond to the picture back

Topics: Java