zl程序教程

您现在的位置是:首页 >  后端

当前栏目

SpringMVC实现文件下载

2023-06-13 09:17:20 时间

文章目录

前言

引入依赖:

 <dependency>
    	<groupId>commons-fileupload</groupId>
    	<artifactId>commons-fileupload</artifactId>
    	<version>1.3.3</version>
    </dependency>
    <dependency>
    	<groupId>commons-io</groupId>
    	<artifactId>commons-io</artifactId>
    	<version>2.2</version>
    </dependency>

前端关键代码:

 <button class="btn btn-w-m btn-primary glyphicon glyphicon-download-alt" type="button"
                                onclick="javascript:downTemplate();">模板下载</button>

Control层代码:

 @RequestMapping(value = "/downloadTemplate")
    public ResponseEntity<byte[]> downTemplate(HttpServletRequest request, @RequestParam("fileName") String fileName,
                                               Model model)throws  Exception{
        //下载文件路径
        String path=request.getSession().getServletContext().getRealPath("/upload/");
        //创建文件对象
        File file=new File(path+File.separator+fileName);
        //设置响应头
        HttpHeaders headers=new HttpHeaders();
        //下载显示的文件名,解决中文名称乱码问题
        String downloadFileName=new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
        //通知浏览器以下载方式(attachment)打开文件
        headers.setContentDispositionFormData("attachment",downloadFileName);
        //定义以二进制流数据(最常见的文件下载)的形式下载返回文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //使用spring mvc框架的ResponseEntity对象封装返回下载数据
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
    }

在downTemplate()方法中,首先根据文件路径和需要下载的文件名来创建文件对象,然后对响应头中文件下载时的打开方式即下载方式进行设置,最后返回ResponseEntity封装的下载结果对象。 使用ResponseEntity对象,可以很方便地定义返回的HttpHeaders和HttpStatus,上面代码中MediaType代表的是Internet Media Type,即互联网媒体类型,也叫做MIME类型。 在Http协议消息头中,使用Content-Type来表示具体请求中的媒体类型信息。HttpStatus类型代表的是Http协议中的状态。

实现效果:

1、点击批量模板下载:

2、可以从左下角看到浏览器成功下载了对应的模板文件。