import javax.servlet.ServletException;标签:文件,java,realPath,resp,import,servlet,javax,下载 From: https://www.cnblogs.com/wangdch/p/17896338.html
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 获取下载文件路径
String realPath = this.getServletContext().getRealPath("E:\\dd.txt");
// 获取文件名称
String fileName = realPath.substring(realPath.lastIndexOf("\\")+1);
// 相应的消息头
resp.setHeader("Content-Disposition","attachment; filename="+ URLEncoder.encode(fileName, "UTF-8"));
// 下载文件的输入流
FileInputStream fileInputStream = new FileInputStream(realPath);
// 创建缓冲区
int len=0;
byte[] buffer = new byte[1024];
// 获取输出流
ServletOutputStream outputStream = resp.getOutputStream();
while ((len=fileInputStream.read(buffer))>0){
outputStream.write(buffer,0,len);
}
fileInputStream.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}