SpringMVC使用ResponseEntity实现文件下载

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

public HttpEntity(T body, MultiValueMap 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">前往testDownloada><br/>

你可能感兴趣的:(springmvc,文件下载)