DS's『 행복합시다 』

Carpe Programming/java

파일 다운로드

nolite 2012. 12. 7. 18:13

<%@ page contentType="application/unknown; charset=euc-kr" %>
<%@ page import="java.util.*,java.io.*"%>
<%
    request.setCharacterEncoding("euc-kr");

    String filename = request.getParameter("filename");
    String filename2 = filename.substring(filename.lastIndexOf("/")+1);
    System.err.println(filename2);

 

    if (filename == null) {
        return;
    }

 

    String mime = getServletContext().getMimeType(filename);

 

    if (mime == null) {
        mime = "application/octet-stream;";
    }

 

    // 자신에게 맞게 수정할 것.
    File file = new File(application.getRealPath(filename));
    byte b[] = new byte[2048];
    response.setContentType(mime);

 

    if(file.length() > 0) {
        if (request.getHeader("User-Agent").indexOf("MSIE 5.5") > -1) {
           response.setHeader("Content-Disposition", "filename=" +filename2 + ";");
        } else {
           response.setHeader("Content-Disposition", "attachment; filename=" + filename2 + ";");
        }

 

       response.setHeader("Content-Length", "" + file.length() );

 

       if (file.isFile()) {
           BufferedInputStream fin = new BufferedInputStream(new FileInputStream(file));
           BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());
           int read = 0;
           while ((read = fin.read(b)) != -1){
               outs.write(b,0,read);
           }
           outs.close();
           fin.close();
        }
    } else {
        out.println("<script>alert('다운로드 파일이 없습니다.');history.back();</script>");
    }
%>

 

728x90