JSP에서 파일 생성 후 파일 다운로드

-- JSP, SPRING 2011. 12. 8. 21:47
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ page import="java.io.*" %>
<%@ page import="java.net.*" %>

<%
    // 파일생성
    File objFile = new File("C:\\test.txt");

    if(objFile.exists()) objFile.delete();

    if(objFile.createNewFile())
    {
        BufferedWriter objBW = new BufferedWriter(new FileWriter(objFile));
        objBW.write("Hello File\r\n");
        objBW.close();
    }

    // 파일 다운로드
    response.setContentType("application/x-msdownload");
    
    String strFileName = URLEncoder.encode(new String(objFile.getName().getBytes("8859_1"), "euc-kr"), "UTF-8");
    response.setHeader("Content-Disposition", "attachment;filename=" + strFileName + ";");
    
    int nRead = 0;
    byte btReadByte[] = new byte[(int)objFile.length()];

    if(objFile.length() > 0 && objFile.isFile())
    {
        BufferedInputStream objBIS = new BufferedInputStream(new FileInputStream(objFile));
        BufferedOutputStream objBOS = new BufferedOutputStream(response.getOutputStream());

        while((nRead = objBIS.read(btReadByte)) != -1)
            objBOS.write(btReadByte, 0, nRead);
    
        objBOS.flush();
        objBOS.close();
        objBIS.close();
    }
%>    
posted by 어린왕자악꿍