🐛 修复 excel 导出的 content-type 和实际文件类型不匹配的问题

This commit is contained in:
b2baccline
2021-08-12 10:58:35 +08:00
parent a6e5da08b7
commit a7296fb5a8

View File

@@ -27,6 +27,8 @@ import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestAttributes;
@@ -76,7 +78,10 @@ public abstract class AbstractSheetWriteHandler implements SheetWriteHandler, Ap
String name = (String) Objects.requireNonNull(requestAttributes).getAttribute(DynamicNameAspect.EXCEL_NAME_KEY, String name = (String) Objects.requireNonNull(requestAttributes).getAttribute(DynamicNameAspect.EXCEL_NAME_KEY,
RequestAttributes.SCOPE_REQUEST); RequestAttributes.SCOPE_REQUEST);
String fileName = String.format("%s%s", URLEncoder.encode(name, "UTF-8"), responseExcel.suffix().getValue()); String fileName = String.format("%s%s", URLEncoder.encode(name, "UTF-8"), responseExcel.suffix().getValue());
response.setContentType("application/vnd.ms-excel"); // 根据实际的文件类型找到对应的 contentType
String contentType = MediaTypeFactory.getMediaType(fileName).map(MediaType::toString)
.orElse("application/vnd.ms-excel");
response.setContentType(contentType);
response.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName); response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName);
write(o, response, responseExcel); write(o, response, responseExcel);