您的位置:首页 > 其它

IO流下载文件,支持中文

2016-06-20 10:38 162 查看
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();

        }

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: