본문 바로가기
개발 업무/JAVA

File을 MultipartFile로 변환

by 호크아이나인 2023. 2. 13.

** 웹스퀘어 임시 폴더에 파일 저장 후 실서버   NAS에 저장 시 활용 

** 기존  Back-end  ,유지를 위한 방법으로 활용 

    // attachList 은 Ajax를 통해 Temp에 저장되어 첨부파일 목록 정보

   
    @SuppressWarnings("finally")
    public int saveUploadFileWsq(List<Map<String, Object>> attachList) {
        int result = 1;

        try {
            BoardFile file = null;
            for ( Map<String, Object> fileMap : attachList) {
                String fileName = fileMap.get("fileName").toString();
                String savePath = fileMap.get("savePath").toString();
                String fileOrgName = fileMap.get("fileOrgName").toString();
                File tempfile = new File(savePath + "/" + fileName);
                if (tempfile.isFile()) {
                    DiskFileItem fileItem = new DiskFileItem("file"
                            ,Files.probeContentType(tempfile.toPath())
                            ,false
                            ,fileOrgName
                            ,(int)tempfile.length()
                            ,tempfile.getParentFile());
                       
                    InputStream input = new FileInputStream(tempfile);
                    OutputStream os = fileItem.getOutputStream();
                    IOUtils.copy(input, os);
                    MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
                    if ( multipartFile.getSize() > 0 ) {
                    }
                    file = null;
                    if( input != null ) input.close();
                    if( os != null ) {
                        os.flush();
                        os.close();
                    }
                }
            }
        } catch (Exception e) {
            result = -1;
            e.printStackTrace();
        } finally {
            ObjectUtils.tempFileDeleteWeq(attachList);
            return files;
        }
    }

    [ObjectUtils.class]
    public static void tempFileDeleteWeq(List<Map<String, Object>> attachList) {
        try {
            for ( Map<String, Object> fileMap : attachList) {
                String fileName = fileMap.get("fileName").toString();
                String savePath = fileMap.get("savePath").toString();
                File file = new File(savePath + "/" + fileName);
                if( file.exists() ) {
                    file.delete();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }