• java之servlet之文件下载


    1.在页面中,可以直接通过超链接来下载:

      a) 如果浏览器能够打开该文件,那么直接在浏览器中显示---不是想要的效果

      b) 任何人都能下载,不能进行权限控制

    2.通过servlet来进行下载,在servlet中是通过文件流来下载的。

    @WebServlet("/download")
    public class DownloadServlet extends HttpServlet{
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("application/octet-stream");
            //解决 以文件形式下载 而不会被浏览器打开    以及中文文件名需要编码
            resp.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode("中国", "utf-8")+".txt");
            PrintWriter os = resp.getWriter();
            String path = this.getServletContext().getRealPath("/download");
            Reader is = new BufferedReader(new FileReader(new File(path,"t.txt")));
            int len=0;
            char[] buffer = new char[200];
            while((len=is.read(buffer))!=-1){
                os.print(new String(buffer,0,len));
            }
            is.close();
            os.close();
        }
    }
  • 相关阅读:
    洛谷P3376 【模板】网络最大流
    bzoj 4598: [Sdoi2016]模式字符串
    JAVA类(下)
    2019DDCTF部分Writeup
    Atom配置(VIM党) · iuunhao
    Tips
    rsync auth failed on module xxx
    基于mykernel完成时间片轮询多道进程的简单内核
    机器学习技法笔记(2)-Linear SVM
    css之制作三角形
  • 原文地址:https://www.cnblogs.com/Vincent-yuan/p/11161240.html
Copyright © 2020-2023  润新知