Servlet实现文件的下载
(1)项目的主文件夹例如以下:(演示出image和servlet的位置所在)
(2)详细实现的代码例如以下:
package com.lc.HttpTest; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class xiazaiwenjian extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); //演示下载文件 response.setHeader("Content-Disposition","attachment;filename=1.jpg"); //打开文件 web网站下载文件的原理 先把文件读进servlet的内存 把文件发送给浏览器段 //字符流仅仅能发文本 字节流发文件 //1获取要下载文件的全路径 String path = this.getServletContext().getRealPath("/images/1.jpg"); //2创建文件传输流 FileInputStream fis = new FileInputStream(path); //做一个缓冲字节数组 byte buff[] = new byte[1024]; int len = 0; //实际每次读取的字节数 OutputStream os = response.getOutputStream(); while((len=fis.read(buff)) > 0){ os.write(buff,0,len); } //关闭 os.close(); fis.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }