Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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 31
Tags more
Archives
Today
Total
관리 메뉴

Formoat's Open Blog

파일 업로드 / 다운로드 본문

Java/JSP & Servlet

파일 업로드 / 다운로드

snd-snd 2019. 9. 10. 22:17

자바는 파일 업로드 / 다운로드 기능을 지원하지 않기때문에 관련 라이브러리를 가져와야 함.

 

1. cos.jar : http://www.servlets.com

 

2. apache commons-fileupload : https://commons.apache.org/proper/commons-fileupload/

 

 

//File Upload Form Tag

<form method="post" enctype="multipart/form-data">
    <input type="file" name="filename"/>
</form>

 

 

# 파일 업로드

// enctype="multipart"로 왔는지 여부 (첨부파일이 있느냐)
boolean isMultipart = ServletFileUpload.isMultipartContent(request);

if(isMultipart) {

    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        List<FileItem> items = upload.parseRequest(request);
        
        for (FileItem item : items) {
        
            if (item.isFormField()) { // 필드 타입 확인 (text, password, contents ...)

            } else { // 필드 타입이 파일이라면 (type="file")
                String fieldName = item.getFieldName(); // 태그 이름 (name="")
                String fileName = item.getName(); // 첨부파일 이름
                long sizeInBytes = item.getSize(); // 파일 사이즈
		
                // IE기반 웹브라우저 경우 파일명에 경로가 추가되어 오기때문에 그 부분을 수정
                fileName = fileName.substring(fileName.lastIndexOf("\\")+1);

                if (!fileName.isEmpty()) {

                    File file = new File("d:/upload/" + fileName); 
                    item.write(file); // 업로드된 파일을 지정한 경로에 저장
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

 

 

 

# 파일 다운로드

String fileName = request.getParameter("fileName");
	
FileInputStream in = new FileInputStream("d:/upload/"+fileName);
	
response.setContentType("application/octet-stream");
	
String agent = request.getHeader("User-Agent");
	
boolean isIE = (agent.contains("MSIE")) || (agent.contains("Trident") ) || (agent.contains("Edge"));
	
if(isIE){
    fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
} else {
    fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
}
			
response.setHeader("Content-Disposition", "attachment;filename="+fileName);
BufferedOutputStream buf = new BufferedOutputStream(response.getOutputStream()); 
	
int read;
byte[] b = new byte[4096];
	
while((read = in.read(b,0,b.length)) != -1){
    buf.write(b,0,read);
}
buf.flush();
buf.close();
in.close();

'Java > JSP & Servlet' 카테고리의 다른 글

에러 처리  (0) 2019.09.15
JSTL - XML 태그  (0) 2019.09.07
JSTL - 데이터베이스 태그  (0) 2019.09.07
JSTL - 함수 태그  (0) 2019.09.07
JSTL - 포맷 태그  (0) 2019.09.07
Comments