MultipartFile Upload an Image Example

 /**
     * Adding data to the general meal master table
     */
    @ApiOperation(value = "Add General Meal Master Table")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "The operation was successful, returning the new general meal master table, which is saved in the data collection element"),
            @ApiResponse(code = 500, message = "Internal error, message returned by msg field")
    })
    @RequestMapping(value = "saveDishesTable",method=RequestMethod.POST)
    @ResponseBody
    public R<DishesTable> saveDishesTable (DishesTable dishesTable, MultipartFile file, HttpServletRequest request){
        try {
            //The full path to this file is divided into two parts: the path to the home folder + the file name

            //Manually create the home folder under 1001-services/src/mian/resources
            //get the path to the downloaded file on the server-> that is, the path to the newly created home folder
            String path = request.getSession().getServletContext().getRealPath("home");
            if(file!=null){
                //Get the name of the file saved to the server
                String fileName = file.getOriginalFilename();
                //splice the path â€" path of home folder + file name
                File dir= new File(path,fileName);
                //write the uploaded file to the specified file on the server
                file.transferTo(dir);
                //returns a canonical pathname string representing the file or directory with the same abstract pathname - "that is, the path is converted to a string form
                String directory = dir.getCanonicalPath();
                //cut the string, starting from the back of the home folder - "get the string corresponding to the filename
                //directory.indexOf("home") means find the subscript of the letter h of home
                //directory.substring(directory.indexOf("home"),directory.length()) means cut from the subscript of h to the last one
                // The result of the final cut is in this form: home/3c2c1cc2-49f1-44c4-b98d-34be8fe09b35.jpg
                String str = directory.substring(directory.indexOf("home"),directory.length());
                dishesTable.setDishesPictures(str);
            }

            DishesTable savedishesTable = dishesTableService.saveDishesTable(dishesTable);
            return R.ok(savedishesTable);
        }catch(Exception e){
            logger.error("Failed to add common meals master table interface error : {}", e);
            e.printStackTrace();
            return R.error("Failed to add common meal master table----->"+e.getMessage());
        }
    }

Read More: