Cheug's Blog

当前位置:网站首页 / JAVA / 正文

Servlet文件下载

2019-05-16 / JAVA / 902 次围观 / 0 次吐槽 /

文件下载

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
    throws ServletException, IOException {
            String filename = "文件.docx";
            
            //下载文件
            String path = "C:/路径/" + filename;
            FileInputStream fis = new FileInputStream(path);
            
            //设置请求头,文件名需要UTF-8编码
            filename = URLEncoder.encode(filename, "UTF-8");
            resp.setHeader("Content-disposition", "attachment;filename=" + filename);
            byte[] bs = new byte[1024];
            ServletOutputStream sos = resp.getOutputStream();
            int len = 0;
            while((len = fis.read(bs)) != -1){
                sos.write(bs, 0, len);
            }
            
            fis.close();
}


Powered By Cheug's Blog

Copyright Cheug Rights Reserved.