`
lipeigege110
  • 浏览: 7497 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

java文件下载

    博客分类:
  • java
 
阅读更多

废话不多说

注意:不能用ajax下载哈,需要用页面请求!

 

public void download() throws IOException {
  String filepath = request.getParameter("downurl");//这个是文件的路径
  String fullFilePath = ServletActionContext.getServletContext()
    .getRealPath(filepath);
  /* 读取文件 */
  File file = new File(fullFilePath);
  /* 如果文件存在 */
  try {
   if (file.exists()) {
    String filename = URLEncoder.encode(file.getName(), "utf-8");
    response.reset();
    response.setContentType("application/x-msdownload");
    response.addHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
    int fileLength = (int) file.length();
    response.setContentLength(fileLength);
    /* 如果文件长度大于0 */
    if (fileLength != 0) {
     /* 创建输入流 */
     InputStream inStream = new FileInputStream(file);
     byte[] buf = new byte[4096];
     /* 创建输出流 */
     ServletOutputStream servletOS = response.getOutputStream();
     int readLength;
     while (((readLength = inStream.read(buf)) != -1)) {
      servletOS.write(buf, 0, readLength);
     }
     inStream.close();
     servletOS.flush();
     servletOS.close();
    }
   }
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 

这个下载是基于servlet实现的。用这种下载文件好些,比晓得地址直接就链接过去。因为这样我只是可以判断用户是否登录或者有没权限什么的

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics