LocalFileConverter.java
10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
package com.bs.reception.utils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.StringUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
/**
* 本地文件转换为MockMultipartFile的完整工具类
*/
public class LocalFileConverter {
// 字段名生成策略
private static final Map<String, Function<String, String>> FIELD_NAME_STRATEGIES = new HashMap<>();
static {
// 根据文件类型生成不同的字段名
FIELD_NAME_STRATEGIES.put("IMAGE", path -> "imageFile");
FIELD_NAME_STRATEGIES.put("AUDIO", path -> "audioFile");
FIELD_NAME_STRATEGIES.put("VIDEO", path -> "videoFile");
FIELD_NAME_STRATEGIES.put("DOCUMENT", path -> "documentFile");
FIELD_NAME_STRATEGIES.put("TEXT", path -> "textFile");
FIELD_NAME_STRATEGIES.put("ARCHIVE", path -> "archiveFile");
}
/**
* 主要转换方法
*/
public static ConversionResult convert(String filePath) {
return convert(filePath, null, null);
}
public static ConversionResult convert(String filePath, String fileName, String fieldName) {
try {
// 验证文件
validateFile(filePath);
// 获取文件信息
FileInfo fileInfo = getDetailedFileInfo(filePath);
// 确定文件名
String actualFileName = determineFileName(fileName, filePath, fileInfo);
// 确定字段名
String actualFieldName = determineFieldName(fieldName, filePath, fileInfo);
// 读取文件内容
byte[] content = Files.readAllBytes(Paths.get(filePath));
// 创建MockMultipartFile
MockMultipartFile multipartFile = new MockMultipartFile(
actualFieldName,
actualFileName,
fileInfo.getContentType(),
content
);
return new ConversionResult(multipartFile, fileInfo);
} catch (IOException e) {
throw new RuntimeException("文件转换失败: " + e.getMessage(), e);
}
}
/**
* 验证文件
*/
private static void validateFile(String filePath) {
if (!StringUtils.hasText(filePath)) {
throw new IllegalArgumentException("文件路径不能为空");
}
File file = new File(filePath);
if (!file.exists()) {
throw new IllegalArgumentException("文件不存在: " + filePath);
}
if (!file.isFile()) {
throw new IllegalArgumentException("路径不是文件: " + filePath);
}
if (!file.canRead()) {
throw new IllegalArgumentException("文件不可读: " + filePath);
}
}
/**
* 获取详细文件信息
*/
private static FileInfo getDetailedFileInfo(String filePath) throws IOException {
Path path = Paths.get(filePath);
File file = new File(filePath);
// 基础信息
String fileName = file.getName();
String extension = getFileExtension(fileName);
long fileSize = file.length();
// Content-Type检测
String contentType = detectContentType(path, extension);
// 文件分类
String category = detectFileCategory(contentType, extension);
return new FileInfo(fileName, extension, contentType, fileSize, category);
}
/**
* 检测Content-Type
*/
private static String detectContentType(Path path, String extension) throws IOException {
// 方法1:使用Files.probeContentType
String contentType = Files.probeContentType(path);
if (StringUtils.hasText(contentType)) {
return contentType;
}
// 方法2:根据扩展名判断
contentType = getContentTypeByExtension(extension);
if (StringUtils.hasText(contentType)) {
return contentType;
}
// 方法3:默认类型
return "application/octet-stream";
}
/**
* 检测文件分类
*/
private static String detectFileCategory(String contentType, String extension) {
if (contentType.startsWith("image/")) return "IMAGE";
if (contentType.startsWith("audio/")) return "AUDIO";
if (contentType.startsWith("video/")) return "VIDEO";
if (contentType.startsWith("text/")) return "TEXT";
if (contentType.contains("pdf") ||
contentType.contains("document") ||
contentType.contains("msword") ||
contentType.contains("excel") ||
contentType.contains("powerpoint")) {
return "DOCUMENT";
}
if (contentType.contains("zip") || contentType.contains("compressed")) return "ARCHIVE";
return "OTHER";
}
/**
* 确定文件名(智能处理)
*/
private static String determineFileName(String providedName, String filePath, FileInfo fileInfo) {
if (StringUtils.hasText(providedName)) {
return providedName;
}
String originalName = fileInfo.getFileName();
// 处理临时文件名(如merged_xxx.mp3)
if (originalName.startsWith("merged_") ||
originalName.startsWith("temp_") ||
originalName.startsWith("tmp_")) {
// 生成更有意义的文件名
return generateMeaningfulFileName(fileInfo);
}
return originalName;
}
/**
* 生成有意义的文件名
*/
private static String generateMeaningfulFileName(FileInfo fileInfo) {
String timestamp = String.valueOf(System.currentTimeMillis());
String extension = fileInfo.getExtension();
switch (fileInfo.getCategory()) {
case "AUDIO":
return "audio_" + timestamp + "." + extension;
case "IMAGE":
return "image_" + timestamp + "." + extension;
case "VIDEO":
return "video_" + timestamp + "." + extension;
case "DOCUMENT":
return "document_" + timestamp + "." + extension;
default:
return "file_" + timestamp + "." + extension;
}
}
/**
* 确定字段名(智能策略)
*/
private static String determineFieldName(String providedFieldName, String filePath, FileInfo fileInfo) {
if (StringUtils.hasText(providedFieldName)) {
return providedFieldName;
}
// 根据文件分类使用策略
Function<String, String> strategy = FIELD_NAME_STRATEGIES.get(fileInfo.getCategory());
if (strategy != null) {
return strategy.apply(filePath);
}
// 默认字段名
return "file";
}
/**
* 根据扩展名获取Content-Type
*/
private static String getContentTypeByExtension(String extension) {
Map<String, String> mimeTypes = createMimeTypeMap();
return mimeTypes.get(extension.toLowerCase());
}
public static void main(String[] args) {
String filePath = "mp3";
System.out.println(getContentTypeByExtension(filePath));
}
/**
* 创建MIME类型映射
*/
private static Map<String, String> createMimeTypeMap() {
Map<String, String> map = new HashMap<>();
// 音频类型
map.put("mp3", "audio/mpeg");
map.put("wav", "audio/wav");
map.put("ogg", "audio/ogg");
map.put("aac", "audio/aac");
map.put("flac", "audio/flac");
map.put("m4a", "audio/mp4");
map.put("wma", "audio/x-ms-wma");
// 图片类型
map.put("jpg", "image/jpeg");
map.put("jpeg", "image/jpeg");
map.put("png", "image/png");
map.put("gif", "image/gif");
map.put("bmp", "image/bmp");
map.put("webp", "image/webp");
map.put("svg", "image/svg+xml");
map.put("ico", "image/x-icon");
// 视频类型
map.put("mp4", "video/mp4");
map.put("avi", "video/x-msvideo");
map.put("mov", "video/quicktime");
map.put("wmv", "video/x-ms-wmv");
map.put("flv", "video/x-flv");
map.put("webm", "video/webm");
map.put("mkv", "video/x-matroska");
map.put("3gp", "video/3gpp");
// 文档类型
map.put("pdf", "application/pdf");
map.put("doc", "application/msword");
map.put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
map.put("xls", "application/vnd.ms-excel");
map.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
map.put("ppt", "application/vnd.ms-powerpoint");
map.put("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
map.put("txt", "text/plain");
map.put("csv", "text/csv");
map.put("xml", "application/xml");
map.put("html", "text/html");
map.put("json", "application/json");
return map;
}
/**
* 获取文件扩展名
*/
private static String getFileExtension(String fileName) {
if (fileName == null) return "";
int lastDot = fileName.lastIndexOf('.');
return (lastDot > 0) ? fileName.substring(lastDot + 1).toLowerCase() : "";
}
/**
* 转换结果类
*/
public static class ConversionResult {
private final MockMultipartFile multipartFile;
private final FileInfo fileInfo;
public ConversionResult(MockMultipartFile multipartFile, FileInfo fileInfo) {
this.multipartFile = multipartFile;
this.fileInfo = fileInfo;
}
public MockMultipartFile getMultipartFile() {
return multipartFile;
}
public FileInfo getFileInfo() {
return fileInfo;
}
}
/**
* 文件信息类
*/
public static class FileInfo {
private final String fileName;
private final String extension;
private final String contentType;
private final long fileSize;
private final String category;
public FileInfo(String fileName, String extension, String contentType, long fileSize, String category) {
this.fileName = fileName;
this.extension = extension;
this.contentType = contentType;
this.fileSize = fileSize;
this.category = category;
}
// Getters
public String getFileName() {
return fileName;
}
public String getExtension() {
return extension;
}
public String getContentType() {
return contentType;
}
public long getFileSize() {
return fileSize;
}
public String getCategory() {
return category;
}
}
}