实现文件的下载源代码如下:
package com.fxl.servlet;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//演示下载文件
response.setHeader("Content-Disposition", "attachment;filename=1.docx");
//打开文件。
//1 获取要下载文件的全路径
String path=this.getServletContext().getRealPath("/1.docx");
//2 创建文件输入流
FileInputStream fis=new FileInputStream(path);
//做一个缓存字节数组
byte buff[]=new byte[1024];
int len=0;//表示实际每次读取了多少个字节
OutputStream os=response.getOutputStream();
while((len=fis.read(buff))>0){
os.write(buff,0,len);
}
//关闭
os.close();
fis.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
如果要下载图片,MP3,视频,只需要修改斜体部分即可。
在浏览器中输入http://localhost:8080/ch08/Servlet2
运行结果如下:(点击下载即可下载的指定目录下)