package com.ard.work.utils.file; import java.io.*; import java.util.Base64; import org.springframework.web.multipart.MultipartFile; public class MultipartFileUtil { /** * 通过InputStream获取MultipartFile */ public static MultipartFile inputStreamToMultipartFile(InputStream inputStream, String fileName, String contentType) { try { byte[] content = inputStream.readAllBytes(); // Java 9+ 可用 return new ByteArrayMultipartFile(content, "file", fileName, contentType); } catch (IOException e) { throw new RuntimeException("输入流转换失败: " + e.getMessage(), e); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { // 忽略关闭异常 } } } /** * 通过文件路径获取MultipartFile */ public static MultipartFile filePathToMultipartFile(String filePath, String fileName, String contentType) { File file = new File(filePath); if (!fileName.contains(".") && filePath.contains(".")) { String extension = filePath.substring(filePath.lastIndexOf('.')); fileName = fileName + extension; } try { byte[] content = java.nio.file.Files.readAllBytes(file.toPath()); return new ByteArrayMultipartFile(content, "file", fileName, contentType); } catch (IOException e) { throw new RuntimeException("文件转换失败: " + e.getMessage(), e); } } /** * Base64字符串转MultipartFile */ public static MultipartFile base64ToMultipartFile(String base64Str, String fileName, String contentType) { if (base64Str == null || base64Str.isEmpty()) { throw new IllegalArgumentException("Base64字符串不能为空"); } String pureBase64Str = base64Str.contains(",") ? base64Str.split(",")[1] : base64Str; try { byte[] fileBytes = Base64.getDecoder().decode(pureBase64Str); return new ByteArrayMultipartFile(fileBytes, "file", fileName, contentType); } catch (IllegalArgumentException e) { throw new RuntimeException("Base64字符串格式非法,解码失败", e); } } /** * 自定义 MultipartFile 实现(不依赖 MockMultipartFile) */ private static class ByteArrayMultipartFile implements MultipartFile { private final byte[] content; private final String name; private final String originalFilename; private final String contentType; public ByteArrayMultipartFile(byte[] content, String name, String originalFilename, String contentType) { this.content = content; this.name = name; this.originalFilename = originalFilename; this.contentType = contentType; } @Override public String getName() { return name; } @Override public String getOriginalFilename() { return originalFilename; } @Override public String getContentType() { return contentType; } @Override public boolean isEmpty() { return content == null || content.length == 0; } @Override public long getSize() { return content.length; } @Override public byte[] getBytes() throws IOException { return content; } @Override public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(content); } @Override public void transferTo(File dest) throws IOException, IllegalStateException { try (FileOutputStream fos = new FileOutputStream(dest)) { fos.write(content); } } } }