MultipartFile 에서 transferto(File file)의 경로 문제 및 해결

질문
오늘 layui 파일 에 올 라 온 컨트롤 을 보고 시도 해 봤 습 니 다.SpringMVC 프로젝트 를 간단하게 만 들 었 습 니 다.설정 파일 에 아래 빈 을 입력 하 십시오.

<!--           -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!--        -->
    <property name="defaultEncoding" value="UTF-8"></property>
    <!--            5MB,5*1024*1024 -->
    <property name="maxUploadSize" value="5242880"></property>
    <!--                ,                ,   10240 -->
    <property name="maxInMemorySize" value="40960"></property>
    <!--           -->
    <property name="uploadTempDir" value="fileUpload/temp"></property>
    <!--        -->
    <property name="resolveLazily" value="true"/>
</bean>
나 는 게 을 러 서 이 속성 들 을 설정 하지 않 고 빈 을 등록 했다.
다음은 내 가 잘못 한 곳 이다.컨트롤 러 코드 를 먼저 올 리 고 프론트 데스크 는 Layui 파일 업로드 모듈 을 통 해 파일 을 업로드 합 니 다.

@ResponseBody
    @RequestMapping("/upload")
    public Map upload(HttpServletRequest request,MultipartFile file){
        HashMap<String,String> map=new HashMap();
        if (!file.isEmpty()) {
            try {
                // getOriginalFilename()           
                String filePath = "D:/upload/test/"+file.getOriginalFilename();
                System.out.println(filePath);
                File saveDir = new File(filePath);
                if (!saveDir.getParentFile().exists())
                    saveDir.getParentFile().mkdirs();
                file.transferTo(saveDir);
                map.put("res","    ");
                return map;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        map.put("res","    ");
        return map;
    }
transferto 방법 에서 전달 하 는 file 이 경로 라면 마지막 경 로 를 파일 이름 으로 하고 접미사 가 없 는 것 입 니 다.이 파일 의 이름 을 바 꾸 고 업로드 파일 과 일치 하 는 접미사 로 변경 하면 열 수 있 습 니 다.
예컨대 나 는

String filePath = "D:/upload/test/"+file.getOriginalFilename();
...로 바꾸다

String filePath = "D:/upload/test";
실행 후 파일 을 열 면 다음 과 같은 것 을 발견 할 수 있 습 니 다:
在这里插入图片描述
transferto 는 내 가 폴 더 로 사용 하고 싶 은 test 를 파일 이름 으로 삼 았 다.접 두 사 를 붙 여 보 겠 습 니 다.jpg
在这里插入图片描述  
업로드 한 파일 과 일치 합 니 다.
마지막 으로 개인 적 으로 들 어 오 는 File 매개 변 수 는 파일 경로 가 아 닌 파일 을 포함 해 야 한 다 는 것 으로 이해 합 니 다.transferTo()는 파일 을 폴 더 에 저장 하지 않 습 니 다.
Multipart File.transferto()가 만난 문제 기록
환경:
  • Springboot 2.0.4
  • JDK8
  • 폼,enctype,input 의 type=file 을 사용 하면 됩 니 다.예 를 들 어 단일 파일 로 업로드 합 니 다.
    
    <form enctype="multipart/form-data" method="POST"
        action="/file/fileUpload">
          <input type="file" name="file" />
        <input type="submit" value="  " />
    </form>
    1.파일 업로드 연결 방식
    #spring.servlet.multipart.location=D:/fileupload1
    
    /**
     *    httpServletRequest    
     * @param  httpServletRequest
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public Map<String, Object> upload(HttpServletRequest httpServletRequest){
        boolean flag = false;
        MultipartHttpServletRequest multipartHttpServletRequest = null;
        //     MultipartHttpServletRequest     (     HttpServletRequest   )
        if(httpServletRequest instanceof MultipartHttpServletRequest){
            multipartHttpServletRequest = (MultipartHttpServletRequest) httpServletRequest;
        }else{
            return dealResultMap(false, "    ");
        }
        //  MultipartFile    (              )
        MultipartFile mf = multipartHttpServletRequest.getFile("file");
        //       
        String fileName = mf.getOriginalFilename();
        //             
        File pfile = new File("D:/fileupload1/");
        if (!pfile.exists()) {
            pfile.mkdirs();
        }
        File file = new File(pfile,  fileName);
       /* //       
        File file = new File(fileName);*/
        try {
            //    
            //                       ,    
            mf.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
            return dealResultMap(false, "    ");
        }
        return dealResultMap(true, "    ");
    }
    /**
     *   Spring MVC multipartFile      
     *
     * @param multipartFile
     * @return
     */
    @PostMapping("/upload/MultipartFile")
    @ResponseBody
    public Map<String, Object> uploadMultipartFile(@RequestParam("file") MultipartFile multipartFile){
        String fileName = multipartFile.getOriginalFilename();
        try {
            //        
            byte [] bytes = multipartFile.getBytes();
            //      (/fileupload1/              )
            File pfile = new File("/fileupload1/");
            //         
            if(!pfile.exists()){
                //    ,     
                pfile.mkdirs();
            }
            //    
            File file = new File(pfile, fileName);
            //       
            OutputStream out = new FileOutputStream(file);
            out.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
            return dealResultMap(false, "    ");
        }
        /*//          ,        (      ,           )
        File file = new File(fileName);
        try {
            //                       ,    
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
            return dealResultMap(false, "    ");
        }*/
        return dealResultMap(true, "    ");
    }
    @PostMapping("/upload/part")
    @ResponseBody
    public Map<String, Object> uploadPart(@RequestParam("file") Part part){
        System.out.println(part.getSubmittedFileName());
        System.out.println(part.getName());
        //   
        InputStream inputStream = null;
        try {
            inputStream = part.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
            return dealResultMap(false, "    ");
        }
        //       
        //1K      
        byte[] bytes = new byte[1024];
        //        
        int len;
        //            
        File pfile = new File("/fileupload1/");
        if (!pfile.exists()) {
            pfile.mkdirs();
        }
        File file = new File(pfile, part.getSubmittedFileName());
        OutputStream out;
        try {
            out = new FileOutputStream(file);
            //    
            while ((len = inputStream.read(bytes)) != -1){
                out.write(bytes, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return dealResultMap(false, "    ");
        } catch (IOException e) {
            e.printStackTrace();
            return dealResultMap(false, "    ");
        }
        /*//              
        //         
        String fileName = part.getSubmittedFileName();
        try {
            //                       ,    
            part.write(fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return dealResultMap(false, "    ");
        }*/
        return dealResultMap(true, "    ");
    }
    
    주의:
    MultipartFile.transferTo()필요 한 상대 경로
    file.transferTo 방법 을 호출 할 때 상대 경로 라면 temp 디 렉 터 리,부모 디 렉 터 리 를 사용 합 니 다.
    첫째,위치 가 맞지 않 고,둘째,부모 디 렉 터 리 가 존재 하지 않 기 때문에 상술 한 오류 가 발생 한다.
    
    //1.             (            );
          //       File f = new File(new File(path).getAbsolutePath()+ "/" + fileName);                  
    //      file.transferTo(f);
          //2.            (/var/falcon/)      (D:/var/falcon/)
          byte [] bytes = file.getBytes();
          OutputStream out = new FileOutputStream(f);
          out.write(bytes);
    
    2.파일 업로드 에 대한 접근
    (1).사용자 정의 ResourceHandler 를 추가 하여 디 렉 터 리 를 발표 합 니 다.
    
    //    Java Config 
    @Configuration
    public class webMvcConfig implements org.springframework.web.servlet.config.annotation.WebMvcConfigurer{
        //    application.properties
        @Value("${file.upload.path}")
        private String path = "upload/";
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            String p = new File(path).getAbsolutePath() + File.separator;//            
            System.out.println("Mapping /upload/** from " + p);
            registry.addResourceHandler("/upload/**") //       
                .addResourceLocations("file:" + p)// springboot    file    
                .setCacheControl(CacheControl.maxAge(30, TimeUnit.MINUTES));//        30  
        }
    }
    
    application.properties 에서 file.upload.path=upload/
    실제 저장 디 렉 터 리
    D:/upload/2019/03081625111.jpg
    (2).Controller 에 RequestMapping 을 추가 하여 출력 흐름 에 파일 을 출력 합 니 다.
    
    @RestController
    @RequestMapping("/file")
    public class UploadFileController {
        @Autowired
        protected HttpServletRequest request;
        @Autowired
        protected HttpServletResponse response;
        @Autowired
        protected ConversionService conversionService;
        @Value("${file.upload.path}")
        private String path = "upload/";    
        @RequestMapping(value="/view", method = RequestMethod.GET)
        public Object view(@RequestParam("id") Integer id){
            //                  ,     id   id
            UploadFile file = conversionService.convert(id, UploadFile.class);//             
            if(file==null){
                throw new RuntimeException("    ");
            }
            
            File source= new File(new File(path).getAbsolutePath()+ "/" + file.getPath());
            response.setContentType(contentType);
            try {
                FileCopyUtils.copy(new FileInputStream(source), response.getOutputStream());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    
    이상 은 개인 적 인 경험 이 므 로 여러분 에 게 참고 가 되 기 를 바 랍 니 다.여러분 들 도 저 희 를 많이 응원 해 주시 기 바 랍 니 다.

    좋은 웹페이지 즐겨찾기