package jp.arcanum.click.pages;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

public class DownloadPage extends AbstractToolPage{

	
	
	public void onPet(){
		
		
		//_path = super.context.getServletContext().getRealPath("") + _path;
		
		String path = (String)super.context.getRequest().getAttribute("DLPATH");
		String filename = path.substring(path.lastIndexOf("/")+1);
		
		//　ファイル名をUTF-8でエンコードする
        //String sFileNm = L01URLEncoder.encode( filename , "UTF-8" ) ;
        
		HttpServletResponse response = super.context.getResponse();
		
        //　HTTPヘッダの指定
        response.setHeader("Content-Disposition",
                "attachment;filename=\"" + filename + "\"");
        //if(contenttype != null){
        //    response.setContentType(contenttype);    
        //}
        
        FileInputStream in = null;
        OutputStream os = null;
        try {
			// ファイルを読み込こんでレスポンスに返す
			File outputFile = new File(path);
			in = new FileInputStream(outputFile);
			os = response.getOutputStream();
			byte[] buffer = new byte[2048];
			int bytes;
			while ((bytes = in.read(buffer, 0, 2048)) != -1) {
			    os.write(buffer, 0, bytes);
			}
		} catch (Exception e) {
			throw new RuntimeException("ダウンロード中に失敗", e);
		}
		finally{
			try {
				if(in!=null)in.close();
			} catch (IOException e) {
				throw new RuntimeException("ダウンロード中のファイルクローズに失敗", e);
			}
		}
		
	}
	


    public String getPath() {
        return null;
    }


}
