zoukankan      html  css  js  c++  java
  • 关于SpingMVC实现文件下载你所不知道的

    文件的上传下载一般在项目中还是非常实用的,此处专门整理一下文件的下载,至于文件的上传实现将在后续中补上。文件的下载多用于模板文件的下载,这在项目中用的还是挺多的。今天用到了就整理出来了,以供搬运工们借鉴并使用,已验证无误。

    (1)     前台实现

    前台实现非常简单,不像文件上传那样复杂,只要给出一个超链接,链接到后台处理的方法,并且需要将文件名传入Controller。

    (2)     后台处理

    后台的Controller就主要处理这样几个问题:

    ①根据文件名,找到模板文件

    ②设置响应的形式、文件头、编码

    ③通过流的形式读取模板文件内容并将之写入输出流

    ④关闭输入输出流

    (3)     下面我们根据前台后台的实现思路来具体看一下实现代码:

    ①前台:

    <a href="${base}/downloadTemplate?fileName=abilityTemplate.xlsx">模板下载</a>

    ②后台:

      @RequestMapping(value = "/downloadTemplate",method = RequestMethod.GET)

        public String downloadAbilityTemplate(String fileName,HttpServletRequest request,HttpServletResponse response){

            response.setCharacterEncoding("utf-8");//设置编码

            response.setContentType("multipart/form-data");//设置类型

            response.setHeader("Content-Disposition", "attachment;fileName="+ fileName);                                       //设置响应头

            try {

            String filePath = Config.getValue("path");

    //获取配置文件中模板文件所在目录

            String path = request.getSession().getServletContext().getRealPath("/")+filePath;

    //获取模板文件的相对目录

            InputStream inputStream = new FileInputStream(new File(path+ File.separator + fileName));

            OutputStream os = response.getOutputStream();

            byte[] b = new byte[2048];

            int length;

            while ((length = inputStream.read(b)) > 0) {

                    os.write(b, 0, length);

            }//边读模板文件边写入输出流

            os.close();

            inputStream.close();//关流

            } catch (FileNotFoundException e) {

                    e.printStackTrace();

            } catch (IOException e) {

                    e.printStackTrace();

            }

            return null;                //注意此时return null

    }

    (4)     注意点:

    ①返回模型层应该是return null,否则出现如下错误:

    java+getOutputStream() has already been called for this response

    ②模板文件的位置可以根据需要存放,只要在后台能获取到此文件的全路径就行

    放在class目录下获取是:

    //获取classes所在路径

    String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();

    //获取WebRoot目录:

    String path = request.getSession().getServletContext().getRealPath("/")

    行走在设计师的路上!
  • 相关阅读:
    左偏树
    论在Windows下远程连接Ubuntu
    ZOJ 3711 Give Me Your Hand
    SGU 495. Kids and Prizes
    POJ 2151 Check the difficulty of problems
    CodeForces 148D. Bag of mice
    HDU 3631 Shortest Path
    HDU 1869 六度分离
    HDU 2544 最短路
    HDU 3584 Cube
  • 原文地址:https://www.cnblogs.com/yolanda-lee/p/4683422.html
Copyright © 2011-2022 走看看