文件下载技术其实就是相当于流拷贝
但是要设置http协议:
resp.setContentType("application/force-download");
resp.setHeader("Content-Disposition", "attachment;filename=***");
//设置HTTP协议响应头,告诉浏览器要用它的下载程序来接收数据(不同的浏览器有自己的默认下载程序,如弹出下载窗口或启动迅雷)。否则就是默认的浏览器直接打开浏览
package cn.hncu.servlet;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse resp)
throws ServletException, IOException {
//设置HTTP协议响应头,告诉浏览器要用它的下载程序来接收数据(不同的浏览器有自己的默认下载程序,如弹出下载窗口或启动迅雷)。否则就是默认的浏览器直接打开浏览
resp.setContentType("application/force-download");
//设置HTTP协议响应头,告诉: 文件名+文件类型
String nm = "美女.jpg"; //如果文件名要支持中文,得进行编码
nm = URLEncoder.encode(nm, "UTF-8");
resp.setHeader("Content-Disposition", "attachment;filename=\""+nm+"\"");
//下载的核心功能: 从服务器本地磁盘把文件数据读取出来 写到 resp.getOutputStream()流中
//imgs/1.jpg
String path = getServletContext().getRealPath("imgs/1.jpg");//起始位置是WebRoot根目录--这里是下载的文件所在的服务器的目录
FileInputStream fin = new FileInputStream(path);
OutputStream out = resp.getOutputStream();
int len=0;
byte b[] = new byte[1024];
while( (len=fin.read(b))!=-1){
out.write(b,0,len);
}
fin.close();
out.close();
}
}