ServletContextDemo4.java文件:(桌面.jpg位于工程的src下)
package com.neu;
import java.io.File;
import java.io.FileInputStream;
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;
/**
* 实现中文文件的下载
* @author wym
*
*/
public class ServletContextDemo4 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//文件在哪?以不变应万变。src中
ServletContext sc = getServletContext();
String realPath = sc.getRealPath("/WEB-INF/classes/桌面.jpg");
//构建文件的输入流
InputStream in = new FileInputStream(realPath);
//告知客户端以下载的方式打开:Content-Disposition=attachment;filename=桌面.jpg
//获取要下载的文件名
String filename = realPath.substring(realPath.lastIndexOf(File.separator)+1);
response.setHeader("Content-Type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(filename,"UTF-8"));
//用response的字节流进行输出
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 {
}
}
运行:http://localhost:8080/ServletDemo/servlet/ServletContextDemo4
结果:浏览器自定下载桌面.jpg文件