下载文件downloadFile

public static void downLoadFile(InputStream inStream, String fileName)
  {
    if (StringUtils.isBlank(fileName)) {
      fileName = UUID.randomUUID().toString().replaceAll("-", "");
    }
    HttpServletRequest req = getRequest();
    String agent = req.getHeader("User-Agent");
    boolean isMSIE = (agent != null) && (agent.indexOf("MSIE") != -1);
    try
    {
      if (isMSIE) {
        fileName = URLEncoder.encode(fileName, "UTF-8");
        fileName = fileName.replace("+", "%20");
      } else {
        fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
      }
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    HttpServletResponse response = getResponse();
    response.setCharacterEncoding("UTF-8");
    response.setHeader("content-disposition", "attachment;filename=\"" + fileName + "\"");
    response.setContentType("application/octet-stream");
    OutputStream outStream = null;
    try {
      outStream = response.getOutputStream();
      byte[] cache = new byte[1024];
      int length = inStream.read(cache);
      while (length != -1) {
        outStream.write(cache, 0, length);
        length = inStream.read(cache);
      }
    } catch (IOException e) {
      e.printStackTrace();
      try
      {
        outStream.flush();
      } catch (IOException e) {
        e.printStackTrace();
      }
      try {
        outStream.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      try {
        inStream.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    finally
    {
      try
      {
        outStream.flush();
      } catch (IOException e) {
        e.printStackTrace();
      }
      try {
        outStream.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      try {
        inStream.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
public static HttpServletRequest getRequest()
  {
    ActionContext ac = ActionContext.getContext();
    HttpServletRequest req = null;
    if (ac != null) {
      req = (HttpServletRequest)ac.get("com.opensymphony.xwork2.dispatcher.HttpServletRequest");
    }

    return req;
  }
public static HttpServletResponse getResponse()
  {
    ActionContext ac = ActionContext.getContext();
    HttpServletResponse response = (HttpServletResponse)ac.get("com.opensymphony.xwork2.dispatcher.HttpServletResponse");
    return response;
  }

 

转载于:https://www.cnblogs.com/sierrajuan/p/4962530.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值