Java中HTTP下载文件——并解决跨域

 


1、常用的需要设置的MIME类型

任何文件(二进制文件) application/octet-stream
.doc application/msword
.dot application/msword
.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
.dotx application/vnd.openxmlformats-officedocument.wordprocessingml.template
.docm application/vnd.ms-word.document.macroEnabled.12
.dotm application/vnd.ms-word.template.macroEnabled.12
.xls application/vnd.ms-excel
.xlt application/vnd.ms-excel
.xla application/vnd.ms-excel
.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xltx application/vnd.openxmlformats-officedocument.spreadsheetml.template
.xlsm application/vnd.ms-excel.sheet.macroEnabled.12
.xltm application/vnd.ms-excel.template.macroEnabled.12
.xlam application/vnd.ms-excel.addin.macroEnabled.12
.xlsb application/vnd.ms-excel.sheet.binary.macroEnabled.12
.ppt application/vnd.ms-powerpoint
.pot application/vnd.ms-powerpoint
.pps application/vnd.ms-powerpoint
.ppa application/vnd.ms-powerpoint
.pptx application/vnd.openxmlformats-officedocument.presentationml.presentation
.potx application/vnd.openxmlformats-officedocument.presentationml.template
.ppsx application/vnd.openxmlformats-officedocument.presentationml.slideshow
.ppam application/vnd.ms-powerpoint.addin.macroEnabled.12
.pptm application/vnd.ms-powerpoint.presentation.macroEnabled.12
.potm application/vnd.ms-powerpoint.template.macroEnabled.12
.ppsm application/vnd.ms-powerpoint.slideshow.macroEnabled.12
.mdb application/vnd.ms-access
.zip application/zip
.tar application/x-tar
//图片
.png image/png
.jpg image/jpeg

2、下载代码

2.1、工具类

encodeFileName方法

2.2、下载

  • 解决跨域不显示在header里面的问题
  • encodeFileName方法见:ExportWordDemo --> com.cc.ewd.download.DownloadUtils#encodeFileName
/** 标准下载的方法
* @param response HttpServletResponse
* @since 2023/5/18 0018
* @author CC
**/
public void standardDownload(HttpServletRequest request, HttpServletResponse response){
try {
//构建好的需要下载的bytes数组
byte[] bytes = new byte[1];
String fileName = "文件名.doc";
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
response.setContentType("image/png;charset=".concat(StandardCharsets.UTF_8.name()));
//Access-Control-Expose-Headers :解决跨域不显示在header里面的问题
response.setHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS,HttpHeaders.CONTENT_DISPOSITION);
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=".concat(
URLEncoder.encode(fileName, StandardCharsets.UTF_8.name())
));
ServletOutputStream out = response.getOutputStream();
out.write(bytes);
out.flush();
out.close();
}catch(Exception e){
e.printStackTrace();
}
}

posted on   C_C_菜园  阅读(433)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示