servlet实现文件下载
程序员文章站
2022-05-24 14:38:18
...
servlet下载文件的原理:
把服务器上的文件以application/octet-stream的响应类型输出到JSP页面。
下载页面download.jsp
Servelt-FileDownloadServlet:
server.xml配置:
下载失败页面:download_error.jsp
把服务器上的文件以application/octet-stream的响应类型输出到JSP页面。
下载页面download.jsp
<body>
<a href="FileDownloadServlet?filename=jd2chm.exe">二进制文件</a><br>
<a href="FileDownloadServlet?filename=test.txt">文本文件</a><br>
<a href="FileDownloadServlet?filename=文件格式兼容包.exe">中文文件名</a><br>
</body>
Servelt-FileDownloadServlet:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FileDownloadServlet extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException
{
String filename = req.getParameter("filename");
if (null == filename || "".equals(filename))
{
resp.sendRedirect("download_error.jsp");
return;
}
// 下载文件
download(req, resp, filename);
}
@SuppressWarnings("deprecation")
private void download(HttpServletRequest req, HttpServletResponse resp, String filename)
throws ServletException, IOException
{
String filePath = req.getRealPath("/upload/" + filename);
File file = new File(filePath);
//请求文件不存在
if (!file.exists())
{
resp.sendRedirect("download_error.jsp");
return;
}
InputStream is = new BufferedInputStream(new FileInputStream(file));
OutputStream os = new BufferedOutputStream(resp.getOutputStream());
//响应类型
resp.setContentType("application/octet-stream");
//解决下载文件中文乱码
filename = new String(filename.getBytes("utf-8"), "ISO-8859-1");
//保存对话框显示的文件名
resp.addHeader("Content-Disposition", "attachment;filename=" + filename);
//保存对话框显示下载文件的大小
resp.addHeader("Content-Length", "" + file.length());
byte[] buff = new byte[1024];
for (int length = 0; -1 != (length = is.read(buff));)
{
os.write(buff, 0, length);
}
os.close();
is.close();
}
}
server.xml配置:
<servlet>
<servlet-name>FileDownloadServlet</servlet-name>
<servlet-class>FileDownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileDownloadServlet</servlet-name>
<url-pattern>/FileDownloadServlet</url-pattern>
</servlet-mapping>
下载失败页面:download_error.jsp
<body>
<h1>下载失败!</h1>
</body>
上一篇: Servlet之文件下载简单实现