springmvc下载那些事

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

(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("/")

行走在设计师的路上!
原文地址:https://www.cnblogs.com/likeju/p/4687209.html