SpringBoot 결합commons-fileupload 파일 업로드

2963 단어 SpringBoot
우선pom 파일에 의존도를 도입합니다.

     commons-fileupload
     commons-fileupload
     1.3.1
 
 
     commons-io
     commons-io
     2.4
 

세부 코드:
    //        
    @Value("${filePath}")
    private String filePath;

    @RequestMapping(value ="/fileUp", method = RequestMethod.POST)
    @ResponseBody
    public void fileUploadOne(@RequestParam("file") MultipartFile file,@RequestParam("fileType") String fileType) {
        //        +  
        String fileName = file.getOriginalFilename();
        //     
        String fname = fileName.substring(0, fileName.lastIndexOf("."));
        //      
        String format = fileName.substring(fileName.lastIndexOf(".") + 1);
        //      (     )
        long MS = System.currentTimeMillis();
        String timeMS = String.valueOf(MS);
        //    +           
        String videoName = fname + "_" + timeMS + "." + format;
        String filelocalPath = "";
        char pathChar = upfilePath.charAt(upfilePath.length() - 1);
        Date date = new Date();
        String dateOne = new SimpleDateFormat("yyyy/MM/dd/").format(date);
        if (pathChar == '/') {
            filelocalPath = upfilePath + dateOne;
        } else {
            filelocalPath = upfilePath + "/" + dateOne;
        }
        File f = new File(filelocalPath);
        if (!f.exists())
            f.mkdirs();
        if (!file.isEmpty()) {
            try {
                FileOutputStream fos = new FileOutputStream(filelocalPath + videoName);
                InputStream in = file.getInputStream();
                //InputStream in = request.getInputStream();
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = in.read(bytes)) != -1) {
                    fos.write(bytes, 0, len);
                }
                fos.close();
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

업로드 파일의 크기를 Application 시작 클래스에서 설정해야 한다는 점도 잊지 마십시오.
 //                   
   @Value("${tempfilePath}")
    private String tempfilePath;

   @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //          
        factory.setMaxFileSize("100MB"); 
        ///           
        factory.setMaxRequestSize("1024MB");
        //        ,                   
        File f = new File(tempfilePath);
        if (!f.exists())
            f.mkdirs();
        factory.setLocation(tempfilePath);
        return factory.createMultipartConfig();

    }

좋은 웹페이지 즐겨찾기