Java文件下载的几种方式

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();
}			



Java的servlet实现文件下载
实现文件下载的java代码



//这是实现下载类(servlet),具体思路代码如下:
//也可连接数据库
package com.message;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class FileDownServlet extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html; charset=GBK";
    //Initialize global variables
    public void init() throws ServletException {
    }
    //Process the HTTP Get request
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        response.setContentType(CONTENT_TYPE);
        //得到下载文件的名字
        //String filename=request.getParameter("filename");
        
        //解决中文乱码问题
        String filename=new String(request.getParameter("filename").getBytes("iso-8859-1"),"gbk");
        //创建file对象
        File file=new File("F://book//WebRoot//"+filename);
        //设置response的编码方式
        response.setContentType("application/x-msdownload");
        //写明要下载的文件的大小
        response.setContentLength((int)file.length());
        //设置附加文件名
       // response.setHeader("Content-Disposition","attachment;filename="+filename);
        
        //解决中文乱码
    response.setHeader("Content-Disposition","attachment;filename="+new String
(filename.getBytes("gbk"),"iso-8859-1"));       
        //读出文件到i/o流
        FileInputStream fis=new FileInputStream(file);
        BufferedInputStream buff=new BufferedInputStream(fis);
        byte [] b=new byte[1024];//相当于我们的缓存
        long k=0;//该值用于计算当前实际下载了多少字节
        //从response对象中得到输出流,准备下载
        OutputStream myout=response.getOutputStream();
        //开始循环下载
        while(k<file.length()){
            int j=buff.read(b,0,1024);
            k+=j;
            //将b中的数据写到客户端的内存
            myout.write(b,0,j);
        }
        //将写入到客户端的内存的数据,刷新到磁盘
        myout.flush();
    }
    //Process the HTTP Post request
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        doGet(request, response);
    }
    //Clean up resources
    public void destroy() {
    }
}



//这是javabean写法 ,主要是实现和数据库连接的,如果没有连接数据库,就可直接不要这
package com;
public class MessageBean {
 private String Message;
 public String getMessage() {
  return Message;
 }
 public void setMessage(String message) {
  Message = message;
 }
}



//HTML页面载入写发,也可连接数据库(案例代码也在)
<%@ page language="java" import="java.util.*,com.message.*" pageEncoding="gbk"%>
<jsp:directive.page import="com.MessageBean;"/>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'book.jsp' starting page</title>
    
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">    
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
  </head>
  
  <body>
    <!--  <a href="java.rar">5.1下载书--java</a> <br>-->
    <%
  //Vector vv=(Vector)session.getAttribute("message");
  //for(int i=0;i<vv.size();i++){
   // MessagesBean mb=(MessagesBean)vv.get(i);
   // out.println("<tr>");
   // out.println("<td>"+mb.getSender()+"</td>");
   // out.println("<td>"+mb.getMess_time()+"</td>");
   // out.println("<td>"+mb.getGeter()+"</td>");
   // out.println("<td>"+mb.getMess_content()+"</td>");
String filename=null;
session.setAttribute("java.rar",filename);
    //取得文件名
   // filename=getFilepath().substring(mb.getFilepath().lastIndexOf("/")+1);
    out.println("<td><a href=FileDownServlet?filename=java.rar>5.1下载书--java</a></td>");//java.rar这个可以改成变量
    out.println("<td><a href=FileDownServlet?filename=dos.rar>dos视频教程</a></td>");
    out.println("<td><a href=FileDownServlet?filename=常用DOS命令.rar>常用DOS命令</a></td>");
    out.println("</tr>");
 // }
  %>
  </body>
</html>


//这是web.xml配置文件,这很重要,不然,很难实现哦
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
 xmlns="http://java.sun.com/xml/ns/j2ee" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>FileDownServlet</servlet-name>
    <servlet-class>com.message.FileDownServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>FileDownServlet</servlet-name>
    <url-pattern>/FileDownServlet</url-pattern>
  </servlet-mapping>
</web-app>







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值