jersey 实现文件下载(以ms word 为例)

使用Jersey难免会碰到下载文件这样的需求,其实实现起来很简单,以微软word文档为例,代码片段如下:

@GET
@Path("download/document")
@Produces("application/vnd.ms-word;charset=utf-8")
public Response downloadDoc(@Context HttpServletRequest request,
		@Context HttpServletResponse response,
		@QueryParam("id") String id){
	String filepath = "D:/test.doc";
	String filename = filepath.substring(filepath.lastIndexOf("/")+1);
	
	File downloadFile = new File(filepath);
	ResponseBuilder responseBuilder = Response.ok((Object) downloadFile);
	try {
		responseBuilder.header("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(filename, "UTF-8"));
	} catch (UnsupportedEncodingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return responseBuilder.build();
}


其中:@Produces("application/vnd.ms-word;charset=utf-8") 的 “application/vnd.ms-word” 官方文档并没有,但是官方文档有“application/vnd.ms-excel”,因此把excel改成word,试验的结果是成功的。另外 java.net.URLEncoder.encode(filename, "UTF-8") 是确保中文文件名不会乱码。
其他类型的文件下载实现相似,只需要修改@Produces 和文件名即可;
.txt ---> @Produces("text/plain")
.pdf ---> @Produces("application/pdf")
.png ----> @Produces("image/png")
.xls ----> @Produces("aapplication/vnd.ms-excel")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值