---
title: "springMVC实现下载文件"
author: "Dragonmandance"
date: "2016-07-28T15:08:24Z"
tags: ["AngularJS", "SpringMVC"]
categories: ["编程语言"]
slug: "springmvc"
draft: false
lastmod: "2016-07-28T15:12:48Z"
id: 2314094
url: "https://dragonmandance.iteye.com/blog/2314094"
---

\[code="java"] 1、前台代码 [](javascript:void%280%29; "导出")$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 \[/code]