springMVC实现下载文件


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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值