Spring MVC File Upload Help

后端 未结 3 1520
名媛妹妹
名媛妹妹 2020-12-15 05:18

I have been integrating spring into an application, and have to redo a file upload from forms. I am aware of what Spring MVC has to offer and what I need to do to configure

3条回答
  •  星月不相逢
    2020-12-15 05:48

    This is what i prefer while making uploads.I think letting spring to handle file saving, is the best way. Spring does it with its MultipartFile.transferTo(File dest) function.

    import java.io.File;
    import java.io.IOException;
    
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    
    @Controller
    @RequestMapping("/upload")
    public class UploadController {
    
        @ResponseBody
        @RequestMapping(value = "/save")
        public String handleUpload(
                @RequestParam(value = "file", required = false) MultipartFile multipartFile,
                HttpServletResponse httpServletResponse) {
    
            String orgName = multipartFile.getOriginalFilename();
    
            String filePath = "/my_uploads/" + orgName;
            File dest = new File(filePath);
            try {
                multipartFile.transferTo(dest);
            } catch (IllegalStateException e) {
                e.printStackTrace();
                return "File uploaded failed:" + orgName;
            } catch (IOException e) {
                e.printStackTrace();
                return "File uploaded failed:" + orgName;
            }
            return "File uploaded:" + orgName;
        }
    }
    

提交回复
热议问题