解决下载直接打开问题

下载也是老生常谈的话题 有时候我们下载的比如pdf 直接打开,或者下载的ofd 是一个压缩包。今天正对这个问题 有一种情况会导致这种情况。

  • 直接打开的伪代码

  StringBuilder fileName = new StringBuilder();//模拟文件名称
  fileName.append(queryByInvoiceId.getInvoiceCode()).append("_").append(queryByInvoiceId.getInvoiceNum()).append(suf);
  OSSClient ossClient = null;
  InputStream  inputStream = null;
  String key = null;
  ServletOutputStream outputStream = null;
  ossClient = AliyunOSSClientUtil.getOSSClient();
  String key = "aliyunkey";
  inputStream = GetInputStream(ossClient, key);
  try {
   outputStream = response.getOutputStream();
   int len = 0;
   byte[] buffer = new byte[4096];
   while ((len = inputStream.read(buffer)) != -1) {
    outputStream.write(buffer, 0, len);
    outputStream.flush();
   }
   response.setCharacterEncoding("UTF-8");
   response.setContentType("application/x-msdownload");//设置下载类型
   response.addHeader("Content-Disposition",
     "attachment;filename=" + fileName);
  } catch (Exception e) {
   // TODO Auto-generated catch block
   logger.error(e.getMessage(),e);
   
  }finally {
   try {
    if(inputStream != null) {
     inputStream.close();
    }
    if(outputStream != null) {
     outputStream.close();
    }
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  • 问题所在

问题所在:其实不难发现代码看似是没有问题,但是在设置response 属性的时候 在 outputStream = response.getOutputStream();获取输出流的时候 还没有设置,导致属性作用不会再输出流体现。知道问题所在 我们就知道我们设置应该是在获取输出流之前设置。

  • 最终伪代码

  StringBuilder fileName = new StringBuilder();
  OSSClient ossClient = null;
  InputStream  inputStream = null;
  String key = null;
  ServletOutputStream outputStream = null;
  ossClient = AliyunOSSClientUtil.getOSSClient();
  String key = "aliyunKey";
  inputStream = GetInputStream(ossClient, key);
  try {
   response.setCharacterEncoding("UTF-8");
   response.setContentType("application/x-msdownload");
   response.addHeader("Content-Disposition",
     "attachment;filename=" + fileName);
   outputStream = response.getOutputStream();
   int len = 0;
   byte[] buffer = new byte[4096];
   while ((len = inputStream.read(buffer)) != -1) {
    outputStream.write(buffer, 0, len);
    outputStream.flush();
   }
  } catch (Exception e) {
   // TODO Auto-generated catch block
   logger.error(e.getMessage(),e);
  }finally {
   try {
    if(inputStream != null) {
     inputStream.close();
    }
    if(outputStream != null) {
     outputStream.close();
    }
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蜗牛乌龟一起走

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值