Skip to content

Commit

Permalink
fix: correct file mime type validation parameter to restore functiona…
Browse files Browse the repository at this point in the history
…lity (#6673)

#### What type of PR is this?
/kind bug
/area core
/milestone 2.20.x

#### What this PR does / why we need it:
修复文件上传时类型校验失效的问题

此问题由 #6390 导致

#### Does this PR introduce a user-facing change?
```release-note
修复文件上传时类型校验失效的问题
```
  • Loading branch information
guqing authored Sep 25, 2024
1 parent 86b95cc commit f6409a0
Showing 1 changed file with 20 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import static run.halo.app.infra.utils.FileUtils.deleteFileSilently;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileAlreadyExistsException;
Expand All @@ -25,6 +26,7 @@
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.MediaType;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
Expand Down Expand Up @@ -156,19 +158,14 @@ private Mono<Void> validateFile(FilePart file, PolicySetting setting) {
var typeValidator = file.content()
.next()
.handle((dataBuffer, sink) -> {
var mimeType = "Unknown";
try {
mimeType = FileTypeDetectUtils.detectMimeType(dataBuffer.asInputStream());
var isAllow = setting.getAllowedFileTypes()
.stream()
.map(FileCategoryMatcher::of)
.anyMatch(matcher -> matcher.match(file.filename()));
if (isAllow) {
sink.next(dataBuffer);
return;
}
} catch (IOException e) {
log.warn("Failed to detect file type", e);
var mimeType = detectMimeType(dataBuffer.asInputStream());
var isAllow = setting.getAllowedFileTypes()
.stream()
.map(FileCategoryMatcher::of)
.anyMatch(matcher -> matcher.match(mimeType));
if (isAllow) {
sink.next(dataBuffer);
return;
}
sink.error(new FileTypeNotAllowedException("File type is not allowed",
"problemDetail.attachment.upload.fileTypeNotSupported",
Expand All @@ -180,6 +177,16 @@ private Mono<Void> validateFile(FilePart file, PolicySetting setting) {
return Mono.when(validations);
}

@NonNull
private String detectMimeType(InputStream inputStream) {
try {
return FileTypeDetectUtils.detectMimeType(inputStream);
} catch (IOException e) {
log.warn("Failed to detect file type", e);
return "Unknown";
}
}

@Override
public Mono<Attachment> delete(DeleteContext deleteContext) {
return Mono.just(deleteContext)
Expand Down

0 comments on commit f6409a0

Please sign in to comment.