2013. 12. 20. 16:52

Servlet 를 이용한 파일 업로드를 간단하게 완성 시켰습니다.

사진과 글이 <Form> 태그를 통해 온 것을 파싱 할 수 있는 MultipartRequest 를 사용했습니다.


1. cos.jar 를 다운 받아 주세요.

 http://www.servlets.com/cos/ 접속해서 받거나 아래 아이콘을 클릭해서 받으면 된다.

cos.jar


2. 파일업로드 서블릿을 생성하고 web.xml파일에 Servlet를 추가해주세요.


public class UploadServlet extends HttpServlet{

public UploadServlet() {

super();

}

public void init() throws ServletException {}

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

FileManager fileManager = new FileManager(req); 

        }


3. FileManager class 를 만들어서 File을 관리할 수 있도록 했습니다.

MultipartRequest Class를 이용하면 File 복사가 되고, 파일명을 바꾸고 싶으면 마지막 파라미터를 주의 깊게 보시면 됩니다.


public class FileManager {

private MultipartRequest mRequest;

private int postMaxSize = 10 * 1024 * 1024;   //10MB

      private String encoding = "UTF-8";

public FileManager(final HttpServletRequest req) throws IOException {

mRequest = new MultipartRequest(req, 이미지저장 Path, postMaxSize, encoding, new FileAlteration());

}

}



4. 마지막 파라미터에 FileAlteration 이라는 class를 inner class 로 생성 했습니다.


class FileAlteration implements FileRenamePolicy {

@Override 

public File rename(File file) {

String parentDir = file.getParent();

String fileName = file.getName();

//Get the extension if the file has one

       String fileExt = "";

       int i = -1;

       if(( i = fileName.indexOf(".")) != -1){

           fileExt = fileName.substring(i);

           fileName = fileName.substring(0,i);

       }

       //Add the timestamp and user ID

       String userId = (String) req.getSession().getAttribute("id");

       newFileName = /*fileName + "_"+ */userId +("_"+( new Date( ).getTime( ) / 1000)) + fileExt;

      

       //piece together the filename

       newFileFullName = parentDir + 

        System.getProperty("file.separator") + newFileName;

       

       file = new File(newFileFullName);

       mimeType = new MimetypesFileTypeMap().getContentType(file);


return file;

}

}



위 소스를 보시면 쉽게 이해하실 수 있을거 같습니다.

파일작성자의 아이디와 TimeStamp 값을 이용해서 새롭게 생성될 파일의 이름을 만들어 주면 됩니다.

아래와 같이 파일이 저장됩니다.




단순한 업로드가 완성 되었습니다.


지금 하고 있는 모바일웹프로젝트에 글과+사진이 함께 전송하도록 하기 위해 한 것입니다.

파일업로드 뿐만 아니라 

게시판테이블에 글 정보 삽입, 방금 삽입된 레코드의 INDEX 를 가져오는 루틴,

파일정보를 담은 테이블에 정보 삽입, 게시판 테이블 UPDATE 까지 고려해야 합니다.





Posted by hoonihoon