IO流下载文件,支持中文

来源:互联网 发布:javascript用户名验证 编辑:程序博客网 时间:2024/05/17 08:40

private String fileName;


    public String getFileName() throws UnsupportedEncodingException {
        return fileName;
    }

    public void setFileName(String fileName) throws UnsupportedEncodingException {
        this.fileName = fileName;
    }


//下载Excel文件

public void downloadexcel() {

        try {

            HttpServletRequest request = ServletActionContext.getRequest();
            HttpServletResponse response = ServletActionContext.getResponse();

            String realPath = ServletActionContext.getServletContext().getRealPath("/upload") + "\\" + fileName;
            System.out.println(realPath);
            File file = new File(realPath);// 得到一个file对象

            if (file.exists()) {

                // 以流方式输出
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/octet-stream");

                setFileDownloadHeader(request, response, fileName);

                InputStream in = new FileInputStream(new File(realPath));
                OutputStream fileOut = response.getOutputStream();
                int b;
                while ((b = in.read()) != -1) {
                    fileOut.write(b);
                }
                in.close();
                fileOut.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
        String userAgent = request.getHeader("USER-AGENT");
        try {
            String finalFileName = null;
            if (userAgent.contains("MSIE")) {// IE浏览器
                finalFileName = URLEncoder.encode(fileName, "UTF8");
            } else if (userAgent.contains("Mozilla")) {// google,火狐浏览器
                finalFileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                finalFileName = URLEncoder.encode(fileName, "UTF8");// 其他浏览器
            }
            response.setHeader("Content-Disposition", "attachment; filename=\"" + finalFileName + "\"");// 这里设置一下让浏览器弹出下载提示框,而不是直接在浏览器中打开
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }


1 0
原创粉丝点击