zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    Easy Climb UVA
    POJ 2823 滑动窗口 单调队列模板
    Feel Good
    Problem J. Joseph’s Problem 约瑟夫问题--余数之和
    hdu 1029 Ignatius and the Princess IV
    poj 1027 Ignatius and the Princess II全排列
    Problem C Updating a Dictionary
    hdu 1412 {A}+{B}
    hdu 4006 The kth great number
    实现:职工管理系统
  • 原文地址:https://www.cnblogs.com/lyh233/p/14008224.html
Copyright © 2011-2022 走看看