web下载文件夹
1、文件下载有两种方式:一种是超链接,一种是Servlet提供下载。
2、超链接下载时:当文件可以在网页直接打开时,会直接打开文件,而不是下载,当文件打开不了时,会提供下载窗口。
3、超链接下载原理
4、Servlet下载文件的原理
5、代码示例
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
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 DownloadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filename = request.getParameter(“filename”); //1 获取要下载的文件名
// 2 把文件所在的文件夹相对路径转成绝对路径
String folderPath = this.getServletContext().getRealPath(“download”);
// 3获得输入流用来将服务器上的文件读出
InputStream is = new FileInputStream(folderPath+”/”+filename);
// 4向相应的头部添加信息,作用是用来弹出保存文件的对话框
//response.setHeader(“Content-Disposition”, “attachment;filename=”+filename);
// 中文文件名下载对话框中将是乱码。处理方式:IE浏览器和其他浏览器的处理方式不同
//IE:
//response.setHeader(“Content-Disposition”, “attachment;filename=”+URLEncoder.encode(filename, “UTF-8”));
//FireFox
String newFilename = new String(filename.getBytes(“UTF-8″),”iso-8859-1”);
response.setHeader(“Content-Disposition”, “attachment;filename=”+newFilename);
// 5写到本地磁盘上
OutputStream os = response.getOutputStream();
int len=0;
byte[] b = new byte[1024];
while((len=is.read(b))!=-1){
os.write(b,0, len);
}
is.close();
os.close();
}
}