2019-08-19

/*文件下载*/

    public static void downloadFile(HttpServletResponse response,String fileName,String path){

        if (fileName != null) {

            //设置文件路径

            File file = new File(path);

            if (file.exists()) {

                response.setHeader("content-type", "application/octet-stream");

                response.setContentType("application/octet-stream");

                try {

                    response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("utf-8"),"ISO-8859-1"));

                } catch (UnsupportedEncodingException e) {

                    e.printStackTrace();

                }

                byte[] buffer = new byte[1024];

                FileInputStream fis = null;

                BufferedInputStream bis = null;

                try {

                    fis = new FileInputStream(file);

                    bis = new BufferedInputStream(fis);

                    OutputStream os = response.getOutputStream();

                    int i = bis.read(buffer);

                    while (i != -1) {

                        os.write(buffer, 0, i);

                        i = bis.read(buffer);

                    }

                } catch (Exception e) {

                    e.printStackTrace();

                } finally {

                    if (bis != null) {

                        try {

                            bis.close();

                        } catch (IOException e) {

                            e.printStackTrace();

                        }

                    }

                    if (fis != null) {

                        try {

                            fis.close();

                        } catch (IOException e) {

                            e.printStackTrace();

                        }

                    }

                }

            }

        }

    }

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容