달력

4

« 2024/4 »

  • 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
2016. 12. 31. 01:59

파일업로드 하는 방법 Javascript & HTML & CSS2016. 12. 31. 01:59

일단 아래와 같은 코드를 html에 넣는다.

multipart/form-data를 빼먹지 말자.


<form action="FileUp" method="POST" enctype="multipart/form-data">

<input type="file" name="image" />

<input type="submit" />

</form>



html코드에 form태그를 추가했으면,

서버에 처리하는 부분을 만들어야 한다.


일단 간단하게 Servlet을 이용한다면,

처리해주는 Servlet 하나 만들고, 접근주소를 위 html에서 준 FileUp으로 주면 된다.



MultipartRequest이용해서 파일 업로드 구현

서블릿에서 받아서 처리하는 부분은 아래 링크를 보면 알 수 있다.

파일에 binary로 직접 써버릴 줄 알았는데, MultipartRequest를 이용해 손쉽게 처리한다.

http://noritersand.tistory.com/132


일단 http://servlets.com/cos/ 여기로 가서 필요 파일을 다운받아서 cos.jar를 프로젝트에 넣자.

그리고 아래와 같이 코드 작성.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

System.out.println("FileUp doPost");

String root = request.getSession().getServletContext().getRealPath("/");

String path = root + "uploadDir";

File file = new File(path);

if(!file.exists()){

file.mkdirs();

}

String encType = "UTF-8";

int maxFileSize = 10 * 1024 * 1024;

MultipartRequest mr = new MultipartRequest(request, path, maxFileSize, encType, new DefaultFileRenamePolicy());


파일이 저장되는 곳은 다음과 같다.

[이클립스 워크스페이스 경로]\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\[프로젝트 이름]\uploadDir


(이렇게 파일을 넣고, DB에 업로드된 파일의 정보를 저장하는 테이블을 만들어서 관리하게 된다)


(이외에 FileUpload라는 API를 이용해서 해도 편리하다.

링크 : http://commons.apache.org/proper/commons-fileupload/using.html )


스프링으로 파일 업로드 구현

http://addio3305.tistory.com/83

:
Posted by 클레잇