首页 » 技术分享 » Swagger怎么下载文件

Swagger怎么下载文件

 

最近在使用Swagger生成项目的API说明文档,其中就碰到了不能下载文件的问题,困惑了我好几天,终于一次意外解决了问题,后面去深入的了解了一下。
错误代码

	@ResponseBody
	@RequestMapping(value = "/downloadInfo")
	@ApiOperation(value = "下载信息", httpMethod = "GET", notes = "下载符合条件的Excel",produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
	public ResultBody downloadInfo(HttpSession session,HttpServletRequest request, HttpServletResponse response) {
		String filename = StringUtil.encodeDownloadFileName("DownloadInfo" + DateUtil.yyyyMMdd.format(new Date()) + ".xlsx", userAgent);
		response.setHeader("Content-disposition", "attachment; filename=" + filename);
		response.setContentType("application/vnd.ms-excel");
	}

使用上面的代码始终不能下载,一直报错:
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
最后看了MediaType中罗列的contentType,发现根本就没有application/vnd.ms-excel,有application/octet-stream,使用流下载文件,最后成功解决不能下载的问题


正确代码

	@ResponseBody
	@RequestMapping(value = "/downloadInfo")
	@ApiOperation(value = "下载信息", httpMethod = "GET", notes = "下载符合条件的Excel",produces = 	MediaType.APPLICATION_OCTET_STREAM_VALUE)
	public ResultBody downloadInfo(HttpSession session,HttpServletRequest request, HttpServletResponse response) {
		String filename = StringUtil.encodeDownloadFileName("DownloadInfo" + DateUtil.yyyyMMdd.format(new Date()) + ".xlsx", userAgent);
		response.setHeader("Content-disposition", "attachment; filename=" + filename);
	}

注意要去掉setContentType
在这里插入图片描述

转载自原文链接, 如需删除请联系管理员。

原文链接:Swagger怎么下载文件,转载请注明来源!

0