文件下载

public ResponseMsg<String> downLoadResource(HttpServletRequest request, HttpServletResponse response) throws IOException {
   URL url = null;
   DataInputStream in=null;
   ServletOutputStream out=null;
   try{
      String resourceId = (String)request.getParameter("resourceId");
      //根据资源id查询资源相关信息
      cn.ulearning.jxpt.resource.domain.Resource resourceInfo = resourceService.getResource(resourceId);
      if(resourceInfo !=null) {
         //文件名字
         String fileName = resourceInfo.getName();
         //文件路径
         String Path = resourceService.getResourceDoloadUrlById(resourceInfo.getResourceCenterId());
         JSONObject filePathJsonObject = JSONObject.parseObject(Path);
         if(filePathJsonObject !=null && filePathJsonObject.containsKey("downloadUrl")) {
            String filePath = ((String)filePathJsonObject.get("downloadUrl"));
            if(null !=filePath && !"".equals(filePath)){
               // 设置response
               response.reset();
               response.setCharacterEncoding("UTF-8");
               response.setContentType("multipart/form--/;charset="+ "UTF-8");
               response.setHeader( "Content-Disposition", "attachment;filename=" + new String( fileName.getBytes(System.setProperty("sun.jnu.encoding","utf-8")), "ISO8859-1" ) );
               // 生成文件输入字节流
               url = new URL(filePath);
               HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
               response.setHeader("Content-Length", ""+urlCon.getContentLength());
               in = new DataInputStream(urlCon.getInputStream());
               // 生成文件输出字节流
               out = response.getOutputStream();
               // 字节数组
               byte[] tmp = new byte[1024];
               // 读取字节长度
               int length = 0;
               while ((length = in.read(tmp)) > 0)
               {
                  out.write(tmp, 0, length);
               }
               out.flush();
            }else{
               return new ResponseMsg<String>(ResponseCode.FAIL,"资源不存在!");
            }
         }
      }else{
         return new ResponseMsg<String>(ResponseCode.FAIL,"资源不存在!");
      }
   }catch(Exception e) {
      logger.error("/downLoadResource-ErrorMsg:",e);
      return null;
   }finally {
      if (out != null) {
         out.close();
      }
      if (in != null) {
         in.close();
      }
   }
   return null;
}

 

Content-Disposition属性有两种类型:inline 和 attachment inline :将文件内容直接显示在页面 attachment:弹出对话框让用户下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值