SpringMVC——文件下载

springMVC提供了一个ResponseEntity类型,可以方便的定义返回的HttpHeads和HttpStatus。

前端:

<a href="javascript:window.location.href='download?fileName=' +
        encodeURIComponent('简历.pdf')">简历.pdf</a>

在FileUploadController中加入下面这个controller

    @RequestMapping("download")
    public ResponseEntity<byte[]> download(HttpServletRequest request,
                                   @RequestParam("fileName") String fileName) throws IOException {
        //下载文件路径
        String path = request.getServletContext().getRealPath("/static/images");
        File file = new File(path+File.separator+fileName);
        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名,解决中文名字乱码问题
        String downloadFileName = new String(fileName.getBytes("utf-8"),"iso-8859-1");
        //通知浏览器已下载方式打开图片
        headers.setContentDispositionFormData("attachment", downloadFileName);
        //二进制数据下载
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        return new ResponseEntity<>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
    }

因为使用了Apache Commons FileUpload组件的FileUtils,所以在pom.xml文件中需要导入common-io依赖

        <!--commons-io可以不用自己导入,fileupload已经依赖了io-->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>
原文地址:https://www.cnblogs.com/lyh233/p/14008224.html