zoukankan      html  css  js  c++  java
  • 下载文件

        @RequestMapping("/downFile")
        public void downFile(HttpServletRequest request, HttpServletResponse response) throws MalformedURLException {
            String s = "http://www.gov.cn/premier/2020-12/14/5569425/images/461c0ea163c94683ac0b0cb7bf4eaf39.jpg";
            URL url = new URL(s);
            File file = new File(s);
            String fileName = file.getName();
            String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
            String agent = (String) request.getHeader("USER-AGENT"); // 判断浏览器类型
            try {
                if (agent != null && agent.indexOf("Fireforx") != -1) {
                    fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1"); // UTF-8编码,防止输出文件名乱码
                } else {
                    fileName = URLEncoder.encode(fileName, "UTF-8");
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
    
            BufferedInputStream bis = null;
            OutputStream os = null;
            response.reset();
            response.setCharacterEncoding("utf-8");
            if (ext == "docx") {
                response.setContentType("application/msword"); // word格式
            } else if (ext == "pdf") {
                response.setContentType("application/pdf"); // word格式
            }
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
    
            try {
                bis = new BufferedInputStream(url.openStream());
                byte[] b = new byte[bis.available() + 1000];
                int i = 0;
                os = response.getOutputStream(); // 直接下载导出
                while ((i = bis.read(b)) != -1) {
                    os.write(b, 0, i);
                }
                os.flush();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
  • 相关阅读:
    人口数据分析
    爬虫:单线程+多任务异步协程
    Python脚本实现在cmd执行相关命令
    Markdown 标记语言指北
    索引/代码块目录
    无题
    [模板] 斯坦纳树
    [模板] 欧拉回路
    [模板] 计算几何2: 自适应Simpson/凸包/半平面交/旋转卡壳/闵可夫斯基和
    [模板] 快速沃尔什变换
  • 原文地址:https://www.cnblogs.com/tjlr/p/14141201.html
Copyright © 2011-2022 走看看