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

    公司经常会用到让用户下载文档并上传,这里提供一个下载表格的功能。

    1.将文件添加到项目中,比如新建包 com.xx.xx.web.exceltpl,添加表格文件。

      该文件放在项目中,会在启动的时候加载到项目的编译空间中

    2使用Thread.currentThread().getContextClassLoader().getResource("/").getPath()获取当前项目的编译路径

        @RequestMapping(value = "downloadTemplate", produces = {"text/javascript;charset=UTF-8"})
        public void downloadTemplate(HttpServletResponse response,HttpServletRequest request){
            //获得当前项目的编译路径
            String classpath=Thread.currentThread().getContextClassLoader().getResource("/").getPath();
            //获得文件路径eg:DEFAULT_ORG_EXCEL_TPL_PATH:/com/xx/xx/web/exceltpl/org_tpl.xls
            File file = new  File(classpath+Constants.DEFAULT_ORG_EXCEL_TPL_PATH);
            //Constants.DEFAULT_ORG_EXCEL_TPL_NAME:学校组织机构模板.xls
            FileUtils.download(file, Constants.DEFAULT_ORG_EXCEL_TPL_NAME, request, response);
        }
    /**
         * 
         * 名称:download<br/>
         * 描述:文件下载 <br/>
         * 
         * @param file
         *            包含文件完整路径的File对象 ,例如new File("c:/yunlu/sch/123456/a.xls")
         * @param fileName
         *            下载后的文件名
         * @param request
         * @param response
         * @return response
         */
        public static HttpServletResponse download(File file, String fileName,
                HttpServletRequest request, HttpServletResponse response) {
            try {
                // 以流的形式下载文件。
                InputStream fis = new BufferedInputStream(new FileInputStream(file));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                response.reset();
                // 设置response的Header
                response.addHeader("Content-Disposition", "attachment;filename="
                        + new String(fileName.getBytes("GBK"), "ISO-8859-1"));
                response.addHeader("Content-Length", "" + file.length());
                OutputStream toClient = new BufferedOutputStream(
                        response.getOutputStream());
                response.setContentType("application/octet-stream");
                toClient.write(buffer);
                toClient.flush();
                toClient.close();
            } catch (IOException ex) {
                file.delete();
                ex.printStackTrace();
            }
            return response;
        }
  • 相关阅读:
    DRF分页器
    DRF版本控制
    crrm复习
    python面试题网络编程和数据库
    python基础面试题
    前端格式
    数据库基本命令
    数据库管理系统
    线程协程和进程
    IPC通信
  • 原文地址:https://www.cnblogs.com/itliucheng/p/4723503.html
Copyright © 2011-2022 走看看