• springMVC实现文件下载


    springMVC框架提供了文件下载的功能,具体操作如下:

     1、在springMVC.xml文件中配置ByteArray转换器

    <mvc:annotation-driven conversion-service="conversionServiceFactoryBean" >
        <mvc:message-converters>
            <!--把ByteArray加在Json前面-->
            <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8" />
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    2、定义controller方法

    @RequestMapping("/exportArrangeCourseInfo")
        public ResponseEntity<byte[]> exportArrangeCourseInfo()throws Exception {
            String pathName = "D:\排课信息.xls";
            File file = new File(pathName);
         String fileName = "教师排课信息.xls"; HttpHeaders headers
    = new HttpHeaders(); //下载显示的文件名,解决中文名称乱码问题 String downloadFielName = new String(filename.getBytes("UTF-8"),"iso-8859-1"); //通知浏览器以attachment(下载方式)打开文件 headers.setContentDispositionFormData("attachment", downloadFielName); //application/octet-stream : 二进制流数据(最常见的文件下载)。 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED); }

    3、页面调用下载链接

    window.location.href="exportArrangeCourseInfo.action"

    这样就可以实现一个简单的文件下载功能了。

    参考:

      http://www.iteye.com/topic/1125784

  • 相关阅读:
    常见错误
    mac安装cocoapods
    WPS复制时删除超链接
    Network | 协议栈
    Leetcode | Remove Duplicates from Sorted Array I && II
    Leetcode | Search in Rotated Sorted Array I & II
    Leetcode | Jump Game I && II
    Leetcode | Combination Sum I && II
    Leetcode | Construct Binary Tree from Inorder and (Preorder or Postorder) Traversal
    Leetcode | Trapping Rain Water
  • 原文地址:https://www.cnblogs.com/leilong/p/9037725.html
Copyright © 2020-2023  润新知