文件的下载主要用到Servlet类和IO流技术。在这里,我创建一个继承HTTPServlet的DownloadServlet类来作为下载文件的业务逻辑处理类,通过接受来自客户端的下载请求,服务器做出响应,进行对应的下载操作,这里用字节流来存储数据,主要涉及到InputStream,OutPutStream。详细请参考下面的主要源代码:
package net.lin.download;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获得要下载的文件的名称
String filename = request.getParameter("filename");
//2.要下载的这个文件的类型--客户端通过文件的MIME类型去区分类型
response.setContentType(this.getServletContext().getMimeType(filename));
//3.告知客户端该文件是以附件(下载)的形式打开
response.setHeader("Content-dispostion", "attachment;filename="+filename);
//4.获取文件的绝对路径
String path=this.getServletContext().getRealPath("download/"+filename);
//5.获得该文件的输入流
InputStream in=new FileInputStream(path);
//6.获得该文件的输出流
ServletOutputStream out=response.getOutputStream();
//7.定义一个整型变量len
int len=0;
//8.定义一个byte数组来接收文件数据
byte [] b=new byte[1024];
while((len=in.read(b))!=-1){
out.write(b, 0, len);
}
in.close();
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}