Servlet 实现文件下载
程序员文章站
2022-05-24 20:51:03
...
文件的下载对于Web应用是必不可少的功能。Servlet实现文件下载只需5步:
- 准备下载的文件,打开文件输入流。
- 获取response响应输出流ServletOutputStream。
- 设置响应头Content-Disposition:attachment;filename=[文件名](此处的filename对应浏览器提示保存文件的文件名)。
- 读文件到响应输出流。
- 关闭输出输入流。
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
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;
@WebServlet(urlPatterns="/download")
public class Download extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String saveFileName = "hahah.txt";
String downloadFile = "C:\\Users\\Administrator\\Desktop\\1234.txt";
resp.setHeader("Content-Disposition", "attachment;filename="+saveFileName);
ServletOutputStream ops = resp.getOutputStream();
FileInputStream fis = new FileInputStream(downloadFile);
BufferedInputStream bis = new BufferedInputStream(fis);
int n; byte[] b = new byte[512];
while((n = bis.read(b))!=-1) {
ops.write(b, 0, n);
}
bis.close();
ops.close();
}
}
上一篇: Servlet实现文件下载