java下载

Posted on 2011-06-14 10:50  LuckCOffey  阅读(1279)  评论(0)    收藏  举报

public HttpServletResponse download(String path, HttpServletResponse response) {
        
try {
            
// path是指欲下载的文件的路径。
            File file = new File(path);
            
// 取得文件名。
            String filename = file.getName();
            
// 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf("."+ 1).toUpperCase();

            
// 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            
byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            
// 清空response
            response.reset();
            
// 设置response的Header
            response.addHeader("Content-Disposition""attachment;filename=" + new String(filename.getBytes()));
            response.addHeader(
"Content-Length""" + file.length());
            OutputStream toClient 
= new BufferedOutputStream(response.getOutputStream());
            response.setContentType(
"application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } 
catch (IOException ex) {
            ex.printStackTrace();
        }
        
return response;
    }

    
public void downloadLocal(HttpServletResponse response) throws FileNotFoundException {
        
// 下载本地文件
        String fileName = "Operator.doc".toString(); // 文件的默认保存名
        
// 读到流中
        InputStream inStream = new FileInputStream("c:/Operator.doc");// 文件的存放路径
        
// 设置输出的格式
        response.reset();
        response.setContentType(
"bin");
        response.addHeader(
"Content-Disposition""attachment; filename=\"" + fileName + "\"");
        
// 循环取出流中的数据
        byte[] b = new byte[100];
        
int len;
        
try {
            
while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 
0, len);
            inStream.close();
        } 
catch (IOException e) {
            e.printStackTrace();
        }
    }

    
public void downloadNet(HttpServletResponse response) throws MalformedURLException {
        
// 下载网络文件
        int bytesum = 0;
        
int byteread = 0;

        URL url 
= new URL("windine.blogdriver.com/logo.gif");

        
try {
            URLConnection conn 
= url.openConnection();
            InputStream inStream 
= conn.getInputStream();
            FileOutputStream fs 
= new FileOutputStream("c:/abc.gif");

            
byte[] buffer = new byte[1204];
            
int length;
            
while ((byteread = inStream.read(buffer)) != -1) {
                bytesum 
+= byteread;
                System.out.println(bytesum);
                fs.write(buffer, 
0, byteread);
            }
        } 
catch (FileNotFoundException e) {
            e.printStackTrace();
        } 
catch (IOException e) {
            e.printStackTrace();
        }
    }

//支持在线打开文件的一种方式
    public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {
        File f 
= new File(filePath);
        
if (!f.exists()) {
            response.sendError(
404"File not found!");
            
return;
        }
        BufferedInputStream br 
= new BufferedInputStream(new FileInputStream(f));
        
byte[] buf = new byte[1024];
        
int len = 0;

        response.reset(); 
// 非常重要
        if (isOnLine) { // 在线打开方式
            URL u = new URL("file:///" + filePath);
            response.setContentType(u.openConnection().getContentType());
            response.setHeader(
"Content-Disposition""inline; filename=" + f.getName());
            
// 文件名应该编码成UTF-8
        } else { // 纯下载方式
            response.setContentType("application/x-msdownload");
            response.setHeader(
"Content-Disposition""attachment; filename=" + f.getName());
        }
        OutputStream out 
= response.getOutputStream();
        
while ((len = br.read(buf)) > 0)
            out.write(buf, 
0, len);
        br.close();
        out.close();
    }
自己在用的一种超链接下载方式:
html页面:
<script >
 //为了下载添加的
 function SaveToLocal() { 
 var pathss=document.getElementById("pathValueHidden").value;
if(pathss.lastIndexOf(".")==-1){
  alert("此文件不存在");
return;
 }else{
 var src ="page/pagel.jsp?path="+pathss; 
document.getElementById("ModifyCameraForm").src = src;  }
}
</script>

<a  href="javascript:void(0)" onclick='SaveToLocal()'>
page.jsp页面:
<%@ page contentType="text/html; charset=utf-8"%>
<%@ page language="java" import="java.io.IOException,java.io.FileOutputStream,java.io.File,java.io.InputStream,java.net.URL,java.net.URLConnection,java.io.OutputStream" pageEncoding="utf-8"%>

<%
//request.setCharacterEncoding("gb2312");
String path = request.getParameter("path"); //ftp路径url//
String name=path.substring(path.lastIndexOf("/")+1,
path.length());
path = new String(path.getBytes("UTF-8"),"UTF-8"); 
response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(name, "UTF-8")); //modify20100303String strUrl = path;
URLConnection uc = null;
try {URL url = new URL(strUrl);
uc = url.openConnection();
uc.setRequestProperty("User-Agent",  "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");  
//uc.setReadTimeout(30000);//获取图片长度  //System.out.println("Content-Length: "+uc.getContentLength()); //获取文件头信息
//System.out.println("Header"+uc.getHeaderFields().toString());  
// if (uc == null)
// return 0;
InputStream ins = uc.getInputStream(); 
byte[] str_b = new byte[1024];  
int byteRead=0;String[] images=strUrl.split("/");
//String imagename=images[images.length-1];
OutputStream fos = response.getOutputStream();
while ((byteRead=ins.read(str_b)) > 0) {
fos.write(str_b,0,byteRead);
};
fos.flush();  
fos.close();}
catch (Exception e) {
e.printStackTrace();
//log.error("获取网页内容出错");
}finally{uc = null;
}
%>
原文地址忘掉啦是在csdn上面的,sorry原作者:以上是我小该了一部分,直接传完整的path就可以啦
以下是另外的一个人的写法原文地址http://long5534.iteye.com/blog/139468
  1. %@ page contentType="text/html;charset=utf-8" %>       
  2. <%@ page import = "java.util.*" %>       
  3. <%@ page import = "java.io.*" %>       
  4. <%@ page import = "java.net.*" %>       
  5. <%       
  6. //防止IE缓存       
  7. response.setHeader("pragma","no-cache");       
  8. response.setHeader("cache-control","no-cache");       
  9. response.setDateHeader("Expires",0);       
  10. //设置编码       
  11. request.setCharacterEncoding("UTF-8");       
  12.       
  13. String fileName = request.getParameter("fileName");       
  14. //取到文件       
  15. File file = new File(application.getRealPath("/")+"upload/" + fileName);       
  16. response.reset();       
  17. //response.setContentType("application/octet-stream;charset=UTF-8");    
  18. response.setContentType("application/octet-stream;charset=GBK");//解决在弹出文件下载框不能打开文件的问题   
  19. //System.out.println(response.getCharacterEncoding());       
  20. //一定要对fileName进行encode       
  21. //response.addHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));    
  22. response.addHeader("Content-Disposition""attachment; filename=" + new String(fileName.getBytes("GBK"),"ISO8859-1"));//解决在弹出文件下载框不能打开文件的问题   
  23. response.setContentLength((int) file.length());       
  24.       
  25. byte[] buffer = new byte[4096];       
  26. BufferedOutputStream output = null;       
  27. BufferedInputStream input = null;       
  28.       
  29. // 写缓冲区:       
  30. try {       
  31.     output = new BufferedOutputStream(response.getOutputStream());       
  32.     input = new BufferedInputStream(new FileInputStream(file));       
  33.       
  34.     int n = (-1);       
  35.     while ((n = input.read(buffer, 04096)) > -1) {       
  36.         output.write(buffer, 0, n);       
  37.     }       
  38.     response.flushBuffer();       
  39. }       
  40. catch (Exception e) {       
  41. // maybe user cancelled download       
  42. finally {       
  43.     if (input != null) input.close();       
  44.     if (output != null) output.close();       
  45. }       
  46. %>   



博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3