response.addHeader("Content-Disposition", "attachment;filename=");
这里的文件名最好用URLDecode.decode(fileName, "UTF-8")处理过,不然中文会有乱码
Servlet例子:
package com.cj.test1_10; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Test9 */ @WebServlet("/Test9") public class Test9 extends HttpServlet { private static final long serialVersionUID = 1L; public Test9() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取文件的绝对路径 String realPath = this.getServletContext().getRealPath("/就来中文.jpg"); System.out.println("realPath:"+realPath); //获取要下载的文件名 String fileName = realPath.substring(realPath.lastIndexOf("\")+1); System.out.println("fileName:"+fileName); //设置响应头,以下载的形式打开文件 response.setHeader("content-disposition", "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8")); //获取要下载的文件输入流 InputStream in = new FileInputStream(realPath); int len = 0; //创建数据缓冲区 byte [] buffer = new byte[1024]; //创建输出流 ServletOutputStream out = response.getOutputStream(); while((len = in.read(buffer))>0){ out.write(buffer, 0, len); } } }