JavaEE实现文件下载
我们先来看一个最简单的文件下载的例子:
package com.yyz.response;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//文件下载
public class ResponseDemo extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String realpath = this.getServletContext().getRealPath("/download/1.gif");
String filename = realpath.substring(realpath.lastIndexOf("\\")+1);
response.setHeader("content-disposition", "attachment;filename="+filename);
//服务器通过这个头,告诉浏览器以下载方式打开数据
FileInputStream in = new FileInputStream(realpath);
int len = 0;
byte buffer[]=new byte[1024];
OutputStream out = response.getOutputStream();
while((len = in.read(buffer))>0){
out.write(buffer, 0, len);
}
in.close();
//out不用close,response在销毁的时候服务器会自动关闭与response相关的流。
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
该段代码的功能是从服务器端下载图片1.png。目录结构用MyEclipse的package explorer显示如下:
让我们增加一点难度,我们要下载的文件是一个中文名字的文件。由于在http协议中头文件中的东西只能是ASCII字符,因而通过上述方式(直接将 String realpath = this.getServletContext().getRealPath("/download/1.gif");改为 String realpath = this.getServletContext().getRealPath("/download/图片.gif");)直接拿文件,
会出现乱码问题。附上测试结果:
要解决这个问题,要用到 URLEncoder类的encode方法:
package com.yyz.response;
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;
//中文文件下载时,中文文件名要经过URL编码。
public class ResponseDemo extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String realpath = this.getServletContext().getRealPath("/download/图片.gif");
String filename = realpath.substring(realpath.lastIndexOf("\\")+1);
response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename,"UTF-8"));
//本函数将字符串以 URL 编码
FileInputStream in = new FileInputStream(realpath);
int len = 0;
byte buffer[]=new byte[1024];
OutputStream out = response.getOutputStream();
while((len = in.read(buffer))>0){
out.write(buffer, 0, len);
}
in.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
附上测试结果:
另外这里有一个小细节需要大家注意: