今天学习的是JavaWeb中最简单的下载,实际就是ServletContext应用之简单下载
下载:其实就是文件的输入与输出,而最头疼的莫过于中国人编程,因为总要考虑到中文乱码或者中文文件下载的问题,下面两个例子希望能帮助到大家学习Servlet中最简单的下载
package cn.itcast.servlet;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//读取资源文件:文件的下载
public class ServletDemo6 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
test2(response);
}
//最简单的文件下载
private void test1(HttpServletResponse response)
throws FileNotFoundException, IOException {
//得到要下载的文件
ServletContext sc = getServletContext();
String path = sc.getRealPath("/f.jpg");//得到文件的真实路径。路径必须以"/"开头,"/"就代表者当前应用
System.out.println(path);
//构建输入流
InputStream in = new FileInputStream(path);
//通知客户端以下载的方式打开
response.setHeader("Content-Disposition", "attachment;filename=f.jpg");
response.setHeader("Content-Type", "application/octet-stream");
//response.getOutputStream()得到输出流
OutputStream out = response.getOutputStream();
int len = -1;
byte b[] = new byte[1024];
while((len=in.read(b))!=-1){
out.write(b, 0, len);
}
in.close();
out.close();
}
//然后就是中文文件下载
private void test2(HttpServletResponse response)
throws FileNotFoundException, IOException {
//得到要下载的文件
ServletContext sc = getServletContext();
String path = sc.getRealPath("/美女.jpg");//得到文件的真实路径。路径必须以"/"开头,"/"就代表者当前应用
//截取文件名 D:\apache-tomcat-6.0.35\webapps\day06\美女.jpg
String filename = path.substring(path.lastIndexOf("\\")+1);
System.out.println(filename);
//构建输入流
InputStream in = new FileInputStream(path);
//通知客户端以下载的方式打开
response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(filename,"UTF-8"));//中文文件名此处要进行URL编码
response.setHeader("Content-Type", "application/octet-stream");
//response.getOutputStream()得到输出流
OutputStream out = response.getOutputStream();
int len = -1;
byte b[] = new byte[1024];
while((len=in.read(b))!=-1){
out.write(b, 0, len);
}
in.close();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
} |