欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springMVC实现下载文件 博客分类: springangularJS FileSaver.jsangularJSspringMVC 

程序员文章站 2024-03-25 16:11:52
...
1、前台代码
<a href="javascript:void(0);" ng-click="exportFile()" title="导出"><i class="icon-download-alt"></i></a>

$scope.exportFile = function() {
    	var temp ={};
        temp.path = "aaa/bbb.txt"
        $http({
            url: contextPath+'/conf/download',
            method: "POST",
            data: JSON.stringify(temp),
            cache: false
        }).success(function(data, status, headers) {
            var octetStreamMime = 'application/octet-stream';
            // Get the headers
            headers = headers();
 
            // Determine the content type from the header or default to "application/octet-stream"
            var contentType = headers['content-type'] || octetStreamMime;


            try
            {
                // Try using msSaveBlob if supported
                console.log("Trying saveBlob method ...");
                var blob = new Blob([data], {type: contentType});
                saveAs(blob, "filename.txt");//这里文件名写死了,可换成需要的文件名
            } catch(ex)
            {
                console.log("saveBlob method failed with the following exception:");
                console.log(ex);
            }
        });
    };

前端使用angularJS、FileSaver.js [url] https://github.com/eligrey/FileSaver.js [/url]

2、后台代码
@RequestMapping(method = RequestMethod.POST,value="/conf/download")
    public ResponseEntity<byte[]> download(@RequestBody Map<String,Object> params){
    	
    	String path = (String)params.get("path");
    	
    	File file = mappingService.getFile(path,type);
    	
    	HttpHeaders headers = new HttpHeaders(); 
    	headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); 
    	headers.setContentDispositionFormData("attachment",path);
    	return new ResponseEntity<byte[]>(RequestUtil.getBytesFromFile(file),headers,HttpStatus.CREATED);
    }

3、配置文件
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
<!--byte数组传输文件-->
                <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
                <bean class = "org.springframework.http.converter.StringHttpMessageConverter">   
                    <property name = "supportedMediaTypes">
                        <list>
                            <value>text/html;charset=UTF-8</value>   
                        </list>   
                    </property>   
                </bean>   
            </list>
        </property>
    </bean>