package ***;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
public class CustomMultipartFile implements MultipartFile {
private final byte[] fileContent;
private final String fileName;
private final String contentType;
public CustomMultipartFile(byte[] fileContent, String fileName) {
this.fileContent = fileContent != null ? fileContent : new byte[0];
this.fileName = fileName;
this.contentType = detectContentType(fileName);
}
public CustomMultipartFile(byte[] fileContent, String fileName, String contentType) {
this.fileContent = fileContent != null ? fileContent : new byte[0];
this.fileName = fileName;
this.contentType = contentType != null ? contentType : detectContentType(fileName);
}
private String detectContentType(String fileName) {
if (fileName == null) {
return "application/octet-stream";
}
try {
// 使用 JDK 的 Files.probeContentType 检测类型
Path tempFile = Files.createTempFile("temp", fileName);
Files.write(tempFile, new byte[0]);
String detectedType = Files.probeContentType(tempFile);
Files.deleteIfExists(tempFile);
if (detectedType != null) {
return detectedType;
}
} catch (IOException e) {
// 忽略异常,使用默认类型
}
// 手动检测常见类型
String lowerName = fileName.toLowerCase();
if (lowerName.endsWith(".jpg") || lowerName.endsWith(".jpeg")) {
return "image/jpeg";
} else if (lowerName.endsWith(".png")) {
return "image/png";
} else if (lowerName.endsWith(".gif")) {
return "image/gif";
} else if (lowerName.endsWith(".pdf")) {
return "application/pdf";
} else if (lowerName.endsWith(".txt")) {
return "text/plain";
}
return "application/octet-stream";
}
@Override
public String getName() {
return "file";
}
@Override
public String getOriginalFilename() {
return fileName;
}
@Override
public String getContentType() {
return contentType;
}
@Override
public boolean isEmpty() {
return fileContent == null || fileContent.length == 0;
}
@Override
public long getSize() {
return fileContent.length;
}
@Override
public byte[] getBytes() throws IOException {
return fileContent;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(fileContent);
}
@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
if (dest == null) {
throw new IllegalArgumentException("目标文件不能为空");
}
if (!dest.getParentFile().exists() && !dest.getParentFile().mkdirs()) {
throw new IOException("无法创建目录: " + dest.getParent());
}
try (FileOutputStream fos = new FileOutputStream(dest)) {
fos.write(fileContent);
}
}
@Override
public void transferTo(Path dest) throws IOException, IllegalStateException {
if (dest == null) {
throw new IllegalArgumentException("目标路径不能为空");
}
Files.createDirectories(dest.getParent());
Files.write(dest, fileContent);
}
}