FileServiceImpl.java
1.5 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
package com.wondertek.service.impl;
import com.wondertek.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @Description:
* @Author W5669
* @Create 2025/7/24
* @Version 1.0
*/
@Service
@Slf4j
public class FileServiceImpl implements FileService {
@Override
public void upload(MultipartFile backupFile, String filePath) throws IOException {
// 检查文件是否为空
if (backupFile.isEmpty()) {
throw new IllegalArgumentException("上传文件为空");
}
// 创建目标文件对象
File dest = new File(filePath);
// 检查目标目录是否存在,不存在则创建
File parentDir = dest.getParentFile();
if (!parentDir.exists()) {
if (!parentDir.mkdirs()) {
throw new IOException("目录创建失败: " + parentDir.getAbsolutePath());
}
}
try {
// 转存文件到指定路径
backupFile.transferTo(dest);
} catch (IOException e) {
throw new IOException("文件写入失败: " + e.getMessage(), e);
} catch (IllegalStateException e) {
throw new IOException("文件状态错误: " + e.getMessage(), e);
}
}
}