Servlet 之文件下载

Servlet 之文件下载

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

public class FileDownload extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String filePath = "文件路径";
        //通过文件路径获取文件名
        String fileName = filePath.substring(filePath.lastIndexOf("\\"));
        resp.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName,"utf-8"));
        FileInputStream in = new FileInputStream(filePath);
        int len;
        //字节数组的大小随各人习惯设置;也可以设置为 in.available() ,如此缓冲区大小刚好,不必再循环读取了
        byte[] bytes = new byte[8];
        ServletOutputStream out = resp.getOutputStream();
        while((len = in.read(bytes)) != -1) {
            out.write(bytes,0,len);
        }
        out.flush();
        out.close();
        in.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
上一篇:引用类型转换


下一篇:javax.websocket.server.ServerContainer not available