티스토리 뷰

Java

파일업로드

LichKing 2014. 12. 23. 10:17

public fileUpload(@RequestParam("file")MultipartFile file){

String filename = file1.getOriginalFilename();
String suffix    = filename.substring(filename.lastIndexOf(".") + 1);
String oldName    = filename.substring(0, filename.lastIndexOf("."));
String newName    = String.valueOf(System.currentTimeMillis());
File path = new File("경로");


FileOutputStream out = null;


        try{
            byte[] fileData = paramFile.getBytes();

            if(!path.exists()){
                path.mkdirs();
            }

            out = new FileOutputStream(path + "/" + newName + "." + suffix);

            out.write(fileData);
        }catch(Exception e){
     
        }finally{
            try{
                out.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }

}


이런식으로 MutipartFile 파입으로 인자를 받고  업로드 처리해주면 됨.

지금 현재의 방법은 spring 을 이용한 방법이고 프레임워크 없이 할경우에는

cos.jar 파일을 이용하여 new MutipartRequest() 로 올려주면 됨.

cos.jar를 이용할 경우에는 파일명을 변환하여 업로드 하는것이 불가능함.

그렇기때문에 중복파일에 대비하여 파일명을 변환하고싶은경우는 파일명 변환 -> 업로드가 아닌 업로드 -> 업로드된 파일명 변환 순으로 해야함.




multi = new MultipartRequest(request, savePath, maxSize, "UTF-8", new DefaultFileRenamePolicy());

            Enumeration enu = multi.getFileNames();
            int i = 0;

            while(enu.hasMoreElements()){
                String paramName    = (String)enu.nextElement();
                String oldFileName    = multi.getFilesystemName(paramName);
                String newFileName    = "";

                if(oldFileName != null){
                    int suffix = oldFileName.lastIndexOf(".");

                    newFileName        = String.valueOf(System.currentTimeMillis()) + i + oldFileName.substring(suffix);
                    File oldFile    = new File(savePath + oldFileName);
                    File newFile    = new File(savePath + newFileName);
                    oldFile.renameTo(newFile);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }


이게 cos.jar를 이용하여 올린 파일.

jsp에서 <form enctype="multipart/form-data">로 submit을 해야함.

그리고 submit을 받는 곳에서 new MultipartRequest를 씀과 동시에 바로 파일업로드는 끝남.

그렇기때문에 위에서 말한것과 같이 업로드 후 파일명을 변환해야한다는것.

renameTo()가 파일명을 바꿔주는 메소드.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함