标签:servlet实现文件的下载 文件传输 字符流 servlet httpservlet
(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); } }
标签:servlet实现文件的下载 文件传输 字符流 servlet httpservlet
原文地址:http://blog.csdn.net/xlgen157387/article/details/39012341