【问题标题】:Whitelisting List of Multipart files in Spring BootSpring Boot中Multipart文件的白名单列表
【发布时间】:2021-06-04 13:47:25
【问题描述】:
我想知道 Spring 包中是否有可用的工具允许我将单个 API 的多种类型列入白名单(即没有内容类型 = 应用程序/pdf),我主要针对图像、文档和声音,我可以知道实施此类检查的最佳做法是什么?
我的 API 旨在通过多部分文件列表接收文件,并在将请求存储到本地文件服务器之前为请求附加一个唯一的 UUID。
我当前的代码允许附加多个多部分文件,希望有一种既定的方法来检查这些文件。
【问题讨论】:
标签:
spring-boot
multipartform-data
whitelist
【解决方案1】:
您可以从MultipartFile 读取内容类型并使用它:
private void checkIfImageType(MultipartFile multipartFile) {
String contentType = multipartFile.getContentType();
if( !contentType.equals("image/jpg")
&& !contentType....) { // Add more checks as needed
throw new RuntimeException("Unsupported content: " + contentType);
}
}
有时,内容类型有额外的东西。在检查内容类型之前,可以使用此辅助方法将其剥离:
private static String stripExtrasFromContentTypeIfNeeded(String contentType) {
int index = contentType.indexOf(';');
if (index != -1) {
contentType = contentType.substring(0, index);
}
return contentType;
}