servletResponse 文件下载
package response;
import java.io.FileInputStream;
import java.io.FileOutputStream;
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 ResponseDemo3 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path = this.getServletContext().getRealPath("/downloads/th.jpeg");
String filename = path.substring(path.lastIndexOf("\\")+1);
//获取下载文件名
// response.setHeader("content-disposition", "attachment;filename="+filename);
//如果下载文件为中文文件,文件名需要url编码
response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename,"utf-8"));
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(path);
int len = 0;
byte[] buf = new byte[1024];
out = response.getOutputStream();
while((len = in.read(buf)) != -1){
out.write(buf, 0, len);
}
}finally{
try {
if(out != null){
out.close();
}
}finally{
try {
if(in != null){
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}