zoukankan      html  css  js  c++  java
  • Servlet下载文件

    1.获取项目根目录:

    @Override
        public void init() throws ServletException {
            // 获取项目在文件系统中的根目录
            string = getServletContext().getRealPath(File.separator);
        }

    init()方法在整个Servlet生命周期内只会被加载一次,用于数据的初始化。

    2.下载文件代码:

    @Override
        protected void doGet(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {
            //配置文件路径
            String filePath = string + "download" + File.separator + "18612.jpg";
            //通过UUID获取宇宙唯一文件名,并将其中‘-’连接符去掉
            String fileName=UUID.randomUUID().toString().replace("-", "");
            // 设置下载文件名
            response.setHeader("content-disposition",
                    "attachment;filename="+fileName+".jpg");
            // 获取输出流
            ServletOutputStream outputStream = response.getOutputStream();
            // 把文件写入tomcat
            InputStream inputStream = new FileInputStream(new File(filePath));
            byte[] b = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(b)) != -1) {
                //输出到浏览器
                outputStream.write(b, 0, len);
            }
            if (inputStream!=null) {
                inputStream.close();
            }
            if (outputStream!=null) {
                outputStream.close();
            }
        }
  • 相关阅读:
    获取随机数
    性能测试工具
    Oracle 级联删除
    一些shell用法
    英文
    主题:【元宵赏灯】蛇年杭州元宵赏灯攻略(上城区、滨江区、下城区)
    CListCtrl 列表选中项非焦点时也是藍色
    ASCII码表
    杭州市公积金提取及相关知识
    ListBox设置水平滚动条
  • 原文地址:https://www.cnblogs.com/mada0/p/4779338.html
Copyright © 2011-2022 走看看