티스토리 뷰

오늘은 파일 업로드 다운로드에 대한 자바 소스에 대한 글을 남겨볼까 합니다. 

늘어렵게만 느꼈던 파일 업로드 그리고 다운로드~!! 막상 해 보니 그리 어렵지 않더군요~!! 


업로드는 Apache 프로젝트인 fileupload를 이용하여 업로드를 하였습니다. jar 파일을 받아서 import 하면 되니까 엄청 편하더라구요~!! 아래 소스도 예제도 친절하게 다 나와 있고, 정말 좋은 것 같습니다. ^^  

아래 URL 확인하시면 됩니다.

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



아래 소스는 파일 업로드 샘플 예제이구요~!! 

public void upload(HttpServletRequest request) throws Exception {

 

// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);

HashMap dataMap = new HashMap();

File tempFile = null;

 
If(!isMultipart) {
       throw new Exception(“Form type is not multipart”);
}
 
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory
.setRepository(TempDirectory);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List<FileItem> items = upload.parseRequest(request);

 

// Process the uploaded items
for(FileItem item:items) {

String fieldName = item.getFieldName();

 

if (item.isFormField()) { // processFormField

            dataMap.put(fieldName, item.getString());

} else {

            if( item.getSize() > 0) tempFile = item;

}

}

 

// Create file object for upload

File uploadFile = new File(savePath + "/" + saveFileName);

              

// Save file object

if(tempFile.getSize() > 0) {

tempFile.write(uploadFile);

tempFile.delete();

}

}



이건 덤으로 다운로드 샘플 예제입니다. 다운로드는 그냥 InputStream을 OutputStream으로 써주는 가장 일반적인 구현방법입니다. 대부분의 다운로드 구현이 아래 방식을 사용하더군요~!! 

public HttpServletResponse download(HttpServletResponse response, String filePath) throws Exception {

File downfile = new File(filePath);

 

if(!downfile.exists()) {

        throw new FileNotFoundException();

}

       

ServletOutputStream outStream = null;

FileInputStream inputStream = null;

       

try {

        outStream = response.getOutputStream();

        inputStream = new FileInputStream(downfile);               

 

        //Setting Resqponse Header

        response.setContentType("application/octet-stream");

        response.setHeader("Content-Disposition",                     

                           "attachment;filename=\""+downfile.getName()+"\"");

              

        //Writing InputStream to OutputStream

        byte[] outByte = new byte[4096];

        while(inputStream.read(outByte, 0, 4096) != -1)

        {

          outStream.write(outByte, 0, 4096);

        }

} catch (Exception e) {

        throw new IOException();

} finally {

        inputStream.close();

        outStream.flush();

        outStream.close();

}

              

return response;

}


최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
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
글 보관함