Example #1
0
  /**
   * 文件下载
   *
   * @param request
   * @param response
   * @throws PageNotFoundException
   * @throws IOException
   * @throws Exception
   */
  @RequestMapping(value = "/download/{fid}")
  public void downloadFile(
      HttpServletRequest request, HttpServletResponse response, @PathVariable long fid)
      throws PageNotFoundException, IOException {
    Attachment file = attachmentService.getFileById(fid);
    if (file == null) {
      throw new PageNotFoundException();
    }

    String fileName = file.getFileName(); // 得到下载文件的名字
    //		int    fileSize = (int) file.getFileSize() * 1024;
    try {
      String agent = WebUtil.getClientInfo(request);
      if (null != agent && -1 != agent.indexOf("MSIE")) {
        fileName = URLEncoder.encode(fileName, "UTF-8");
        fileName = StringUtil.replace(fileName, "+", "%20");
      } else {
        fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
        //        		fileName = StringUtil.replace(fileName, " ", "%20");
      }
    } catch (UnsupportedEncodingException e1) {
      e1.printStackTrace();
    }
    response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
    response.setContentType(FileUploadUtil.getFileMimeType(file.getFileType())); // 设置response的编码方式
    //	    response.setContentLength( fileSize ); // 暂时去除文件大小的输出,防止浏览器接受数据不完整

    try {
      OutputStream myout = response.getOutputStream(); // 从response对象中得到输出流,准备下载
      FileInputStream fis = new FileInputStream(file.getFileUrl()); // 读出文件到i/o流
      BufferedInputStream buff = new BufferedInputStream(fis);
      int read = 0;
      byte[] temp = new byte[1024]; // 相当于我们的缓存
      while ((read = buff.read(temp)) != -1) {
        myout.write(temp, 0, read);
      }
      // 将写入到客户端的内存的数据,刷新到磁盘
      myout.flush();
      buff.close();
      myout.close();
    } catch (IOException e) {
      log.error("download error, file id is " + fid, e);
      throw e;
    }
  }
Example #2
0
 /**
  * 文件下载
  *
  * @param request
  * @param response
  * @throws PageNotFoundException
  * @throws IOException
  * @throws Exception
  */
 @RequestMapping(value = "/download")
 public String downloadFile(HttpServletRequest request) throws PageNotFoundException, IOException {
   long fid = WebUtil.getValueLong(request, "fid", -1);
   return "redirect:/system/attachment/download/" + fid;
 }