SpringMVC使用ResponseEntity实现文件下载

上一篇写了文件上传,文件下载的配置过程同文件上传,有需要的请http://blog.csdn.net/c______________/article/details/77512017
本文主要通过ResponseEntity<byte[]>实现文件下
该类实现响应头、文件数据(以字节存储)、状态封装在一起交给浏览器处理以实现浏览器的文件下载。
ResponseEntity参数解释:ResponseEntity(T body, MultiValueMap<String, String> headers, HttpStatus statusCode)
其中ResponseEntity<T> extends HttpEntity<T>,很明显的继承关系,HttpEntity是一个实体类,在new ResponseEntity<byte[]>(b, headers, statusCode);这句初始化的时候,会将T body, MultiValueMap<String, String> headers两个参数传给父类,本类中存放状态码,在HttpEntity类的源码中可以看到:

public HttpEntity(T body, MultiValueMap<String, String> headers) {
        this.body = body;
        HttpHeaders tempHeaders = new HttpHeaders();
        if (headers != null) {
            tempHeaders.putAll(headers);
        }
        //将header头转变成只能读取的对象,而不是写入的对象。
        this.headers = HttpHeaders.readOnlyHttpHeaders(tempHeaders);
    }

HttpHeaders类说明:表示HTTP请求和响应头,将字符串头名映射到字符串值的列表。
在这里为什么要用HttpHeaders类,是因为MultiValueMap接口的实现类是:HttpHeaders、LinkedMultiValueMap以及静态类MultiValueMapAdapter
话不多说直接上代码:

//下载练习
    @RequestMapping(value="/testDownload")
    public ResponseEntity<byte[]>  testDownload(HttpServletRequest request){
        String filename="cccc.jpg";
        ServletContext scontext=request.getServletContext();
        String path=scontext.getRealPath("/WEB-INF/file/"+filename);
        System.out.println(path);
        File f=new File(path);
        InputStream in;
        ResponseEntity<byte[]> response=null ;
        try {
            in = new FileInputStream(f);
            byte[] b=new byte[in.available()];
            in.read(b);
            HttpHeaders headers = new HttpHeaders();
            filename = new String(filename.getBytes("gbk"),"iso8859-1");
            headers.add("Content-Disposition", "attachment;filename="+filename);
            HttpStatus statusCode=HttpStatus.OK;
            response = new ResponseEntity<byte[]>(b, headers, statusCode);  
            in.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return response;
    }

请求jsp代码:

文件下载:
<a href="${pageContext.request.contextPath }/testDownload">前往testDownload</a><br/>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值