springMVC实现下载文件

阅读更多
1、前台代码


$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 download(@RequestBody Map 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(RequestUtil.getBytesFromFile(file),headers,HttpStatus.CREATED);
    }

3、配置文件

        
            

                
                
                   
                    
                        
                            text/html;charset=UTF-8   
                           
                       
                   
            
        
    

你可能感兴趣的:(FileSaver.js,angularJS,springMVC)