浏览器下载附件

12 篇文章 0 订阅
  • 第一种
public void downPrintFile(String fileName, InputStream is, HttpServletRequest request, HttpServletResponse response) {
   try (
            BufferedInputStream bis = new BufferedInputStream(is);
            BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())
    ) {
        request.setCharacterEncoding("UTF-8");
        String agent = request.getHeader("User-Agent").toUpperCase();
        if ((agent.indexOf("MSIE") > 0) || ((agent.contains("RV")) && (!agent.contains("FIREFOX"))))
            fileName = URLEncoder.encode(fileName, "UTF-8");
        else {
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1");
        }
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment; filename=" + fileName);
        byte[] buff = new byte[2048];
        int bytesRead;
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }
        System.out.println("success");
        bos.flush();
    } catch (Exception e) {
        System.out.println("附件下载失败!");
    }
}
  • 第二种
public void downloadTemplate(HttpServletRequest request, HttpServletResponse response) {
   String fileName = "导入模板.xlsx";
   //设置编码格式
   response.setCharacterEncoding("UTF-8");
   response.setHeader("content-type", "application/octet-stream");
   response.setContentType("application/octet-stream;charset=utf-8");

   String userAgent = request.getHeader("User-Agent");
   String formFileName=fileName;
   //文件名设置编码格式
   try {
       // 针对IE或者以IE为内核的浏览器
       if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
           formFileName = java.net.URLEncoder.encode(formFileName, String.valueOf(StandardCharsets.UTF_8));
       } else {
           // 非IE浏览器的处理
           formFileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
       }
   } catch (UnsupportedEncodingException e) {
       e.printStackTrace();
   }
   response.setHeader("Content-Disposition", "attachment;filename=" + formFileName);
   String filePath = Objects.requireNonNull(Thread.currentThread().getContextClassLoader().getResource("")).getPath() + fileName;
   logger.info("导入模板的filePath=========》" + filePath);

   File file = new File(filePath);
   if (!file.exists()) {
       throw new BusinessException("下载失败,模板未找到!");
   }
   try (
           InputStream is = new FileInputStream(file);
           OutputStream os = response.getOutputStream();
           BufferedInputStream bis = new BufferedInputStream(is)) {
       byte[] buff = new byte[1024];
       int i = bis.read(buff);
       while (i != -1) {
           os.write(buff, 0, buff.length);
           os.flush();
           i = bis.read(buff);
       }
   } catch (FileNotFoundException e1) {
       throw new BusinessException("模板未找到!");
   } catch (IOException e) {
       throw new BusinessException("模板下载失败!");
   }
}
  • 前端请求
// 动态生成a标签,自动下载文件
const a = document.createElement('a');
a.style.display = 'none';
a.download = '导入模板.xlsx';
a.href = '/api/attachDownload/downloadTemplate';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值