Springboot下载word文件无法打开
错误

话不多说直接上代码,正确word下载方式
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
/**
* 网络word文件获取到服务器后,经服务器处理后响应给前端
*
* @param fileUrl
* @param filename
* @param response
* @功能描述 网络文件获取到服务器后,经服务器处理后响应给前端
*/
@RequestMapping("/netDownLoadNet")
public void netDownLoadWordNet(String fileUrl, String filename, HttpServletResponse response) throws Exception {
URL url = new URL(fileUrl);
URLConnection conn = url.openConnection();
InputStream inputStream = conn.getInputStream();
response.setContentType(conn.getContentType());
//纯下载方式 文件名应该编码成UTF-8
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
XWPFDocument document = new XWPFDocument(OPCPackage.open(inputStream));
document.write(response.getOutputStream());
inputStream.close();
}
本文档探讨了在Springboot应用中遇到的无法打开下载Word文件的问题。通过提供一段关键代码示例,展示了如何正确处理网络word文件的下载流程,包括设置Content-Type,Content-Disposition以及使用XWPFDocument读写文件。问题的关键在于正确处理文件流并确保文件内容完整无损地传输给前端。
1万+

被折叠的 条评论
为什么被折叠?



