Servlet文件下载案例

tech2024-04-16  93

代码实现

package test; import jakarta.servlet.ServletContext; import jakarta.servlet.ServletException; import jakarta.servlet.ServletOutputStream; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.IOException; @WebServlet("/downloadservlet") public class DownLoadServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获得参数filename的值来确定资源 String filename = req.getParameter("filename"); //获得web对象ServletContext ServletContext servletContext = this.getServletContext(); //获得filename所在web中的真实路径 String realPath = servletContext.getRealPath("/img/" + filename); //读取对应资源 FileInputStream fis = new FileInputStream(realPath); //获取资源MIME类型,例.jpg = image/jpeg String mimeType = servletContext.getMimeType(filename); //设置响应头 resp.setHeader("content-type" , mimeType); //content-disposition资源以附件形式呈现,filename为下载框中资源名称 resp.setHeader("content-disposition" , "attachment;filename=" + filename); //将资源下载 byte[] buff = new byte[1024 * 8]; int len = 0; ServletOutputStream sos = resp.getOutputStream(); while((len = fis.read(buff)) != -1){ sos.write(buff , 0 , len); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req , resp); } }

HTML文件

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a href="img/1.jpg">图片</a> <a href="img/1.gif">视频</a> <hr> <a href="/HTTP/downloadservlet?filename=1.jpg">图片</a> <a href="/HTTP/downloadservlet?filename=1.gif">视频</a> </body> </html>
最新回复(0)