1. 文件名非中文:
package ztq.servlet.study; import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream; 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 ServletDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取要下载的文件
ServletContext sc = getServletContext();
String path = sc.getRealPath("/pic.jpg"); //通知客户端以下载的方式打开
response.setHeader("Content-Disposition", "attachment;filename = pic.jpg" );
response.setHeader("Content-type", "application/octet-stream"); //构建输入输出流
InputStream in = new FileInputStream(path);
OutputStream out = response.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while((len = in.read(buf)) != -1){
out.write(buf, 0, len);
}
in.close();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
2. 文件名含中文:
package ztq.servlet.study; 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; public class ServletDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取要下载的文件
ServletContext sc = getServletContext();
String path = sc.getRealPath("/人物.jpg"); //截取文件名
String filename = path.substring(path.lastIndexOf("\\") + 1); //通知客户端以下载的方式打开
response.setHeader("Content-Disposition", "attachment;filename = " + URLEncoder.encode(filename, "UTF-8"));
response.setHeader("Content-type", "application/octet-stream"); //构建输入输出流
InputStream in = new FileInputStream(path);
OutputStream out = response.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while((len = in.read(buf)) != -1){
out.write(buf, 0, len);
}
in.close();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}