servlet学习笔记3---文件下载

  1. inputstream读取服务器上的文件
  2. outputstream通过response数据格式设置和浏览器将文件写到客户端
  3. 静态资源放在idea工程的web根目录下,编译后会在out文件夹中生成到静态资源目录
  4. 注意response的setheader的属性设置,告诉浏览器以文件的形式打开
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

public class serv extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //
        downloadChineseFileByOutputStream(resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    private void downloadChineseFileByOutputStream(HttpServletResponse response)
            throws FileNotFoundException, IOException {
                System.out.println("get it");
                String realPath = this.getServletContext().getRealPath("/img/1.jpg");//获取要下载的文件的绝对路径
                System.out.println(realPath);
               String fileName = realPath.substring(realPath.lastIndexOf("\\")+1);//获取要下载的文件名
                //设置content-disposition响应头控制浏览器以下载的形式打开文件,中文文件名要使用URLEncoder.encode方法进行编码,否则会出现文件名乱码
                response.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
                InputStream in = new FileInputStream(realPath);//获取文件输入流
               int len = 0;
                 byte[] buffer = new byte[1024];
                 OutputStream out = response.getOutputStream();
                 while ((len = in.read(buffer)) > 0) {
                         out.write(buffer,0,len);//将缓冲区的数据输出到客户端浏览器
                     }
                 in.close();
                System.out.println(realPath);
                System.out.println(fileName);

             }
}
上一篇:文件下载


下一篇:文件上传和下载