package com.engine.htsc.payment.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class DownLoadPaymentTemplateAction  extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        this.doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        OutputStream outputStream =null;
        InputStream inputStream =null;
        try {
            req.setCharacterEncoding("utf-8");
            String fileName = req.getParameter("fileName");
            String fileName_cn = "付款明细模板.xlsx";//req.getParameter("fileNameCN");
            fileName= URLDecoder.decode(fileName,"UTF-8");
            String filePath = System.getProperty("sysRootDir") + File.separator + "WEB-INF" + File.separator + "paymenttemplate" + File.separator + fileName;
            File file = new File(filePath);
            if(file.exists()){
                if (req.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                    fileName_cn = URLEncoder.encode(fileName_cn, "UTF-8");
                } else {
                    fileName_cn = new String(fileName_cn.getBytes("UTF-8"), "ISO8859-1");
                }
                resp.setHeader("Content-Disposition","attachment;filename=\""+fileName_cn+"\"");
                outputStream = resp.getOutputStream();
                inputStream = new FileInputStream(file);
                byte b [] =new byte[1024];
                int length=0;
                while (-1!=(length=inputStream.read(b, 0, b.length))) {
                    outputStream.write(b,0,length);
                }
                resp.flushBuffer();
            }else{
                resp.setContentType("text/html;charset=utf-8");
//                resp.setCharacterEncoding("utf-8");
                resp.getWriter().write("<h3>没有找到需要的文件<h3>");
                resp.flushBuffer();
            }
        } catch (Exception e) {
        }finally{
            if(null!=inputStream){
                inputStream.close();
            }
            if(null!=outputStream){
                outputStream.close();
            }
        }
    }
}
