最近在使用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活动:慈云数据爆款香港服务器,CTG+CN2高速带宽、快速稳定、平均延迟10+ms 速度快,免备案,每月仅需19元!! 点击查看.yyyyMMdd.format(new Date()) + \”.xlsx\”, userAgent);response.setHeader(\”Content-disposition\”, \”attachment; filename=\” + filename);}
注意要去掉setContentType
59433596
《swagger怎么用,swagger怎么读》来自互联网同行内容,若有侵权,请联系我们删除!
还没有评论,来说两句吧...