Administrator
5 days ago 059892a0ac18e8c5739b43e02411e4d7dc9cbfdd
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
package cc.mrbird.febs.ai.controller.fileUpload;
 
import cc.mrbird.febs.common.controller.BaseController;
import cc.mrbird.febs.common.entity.FebsResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
 
/**
 * @author Administrator
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/fileUpload")
public class FileUploadController extends BaseController {
 
    // @Value("${file.upload.dir}")
    private String uploadDir = "d:/upload/files";
 
    // @Value("${file.chunk.dir}")
    private String chunkDir = "d:/upload/chunks";
 
    /**
     * 上传文件分片
     */
    @PostMapping("/uploadChunk")
    public FebsResponse uploadChunk(@RequestParam("file") MultipartFile file,
                                    @RequestParam("fileName") String fileName,
                                    @RequestParam("chunk") int chunk,
                                    @RequestParam("chunks") int chunks,
                                    @RequestParam("fileMd5") String fileMd5) {
        try {
            // 确保分片目录存在
            Path chunkPath = Paths.get(chunkDir, fileMd5);
            if (!Files.exists(chunkPath)) {
                Files.createDirectories(chunkPath);
            }
 
            // 保存分片文件
            Path chunkFilePath = chunkPath.resolve(chunk + ".part");
            Files.write(chunkFilePath, file.getBytes());
 
            return new FebsResponse().success().message("分片上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new FebsResponse().fail().message("分片上传失败: " + e.getMessage());
        }
    }
 
    /**
     * 合并文件分片
     */
    @PostMapping("/mergeChunks")
    public FebsResponse mergeChunks(@RequestParam("fileName") String fileName,
                                    @RequestParam("fileMd5") String fileMd5,
                                    @RequestParam("chunks") int chunks) {
        try {
            // 确保上传目录存在
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
 
            // 生成唯一文件名
            String uniqueFileName = UUID.randomUUID().toString() + "_" + fileName;
            Path targetFilePath = uploadPath.resolve(uniqueFileName);
 
            // 确保分片目录存在
            Path chunkPath = Paths.get(chunkDir, fileMd5);
            if (!Files.exists(chunkPath)) {
                return new FebsResponse().fail().message("分片目录不存在");
            }
 
            // 合并分片
            try (FileOutputStream outputStream = new FileOutputStream(targetFilePath.toFile())) {
                for (int i = 0; i < chunks; i++) {
                    Path chunkFilePath = chunkPath.resolve(i + ".part");
                    if (!Files.exists(chunkFilePath)) {
                        return new FebsResponse().fail().message("分片文件不存在: " + chunkFilePath);
                    }
                    byte[] chunkBytes = Files.readAllBytes(chunkFilePath);
                    outputStream.write(chunkBytes);
                    // 删除已合并的分片
                    Files.deleteIfExists(chunkFilePath);
                }
            }
 
            // 删除分片目录
            Files.deleteIfExists(chunkPath);
 
            // 保存文件信息到数据库或文件系统(这里简化处理)
            saveFileInfo(uniqueFileName, targetFilePath.toFile().length());
 
            return new FebsResponse().success().message("文件上传成功").data(uniqueFileName);
        } catch (Exception e) {
            e.printStackTrace();
            return new FebsResponse().fail().message("文件合并失败: " + e.getMessage());
        }
    }
 
    /**
     * 播放视频文件
     */
    @GetMapping("/play/{fileName}")
    public void playVideo(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        try {
            Path filePath = Paths.get(uploadDir, fileName);
            if (!Files.exists(filePath)) {
                response.setStatus(HttpStatus.NOT_FOUND.value());
                return;
            }
 
            // 设置响应头
            response.setContentType("video/mp4");
            response.setContentLengthLong(Files.size(filePath));
            response.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");
 
            // 流式传输文件
            try (InputStream inputStream = Files.newInputStream(filePath);
                 OutputStream outputStream = response.getOutputStream()) {
                byte[] buffer = new byte[8192];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
    }
 
    /**
     * 获取文件列表
     */
    @GetMapping("/list")
    public FebsResponse getFileList() {
        try {
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                return new FebsResponse().data(new ArrayList<>());
            }
 
            List<FileInfo> fileList = new ArrayList<>();
            Files.list(uploadPath).forEach(path -> {
                if (Files.isRegularFile(path)) {
                    try {
                        FileInfo fileInfo = new FileInfo();
                        fileInfo.setFileName(path.getFileName().toString());
                        fileInfo.setFileSize(Files.size(path));
                        fileInfo.setUploadTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(Files.getLastModifiedTime(path).toMillis())));
                        fileList.add(fileInfo);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
 
            return new FebsResponse().success().data(fileList);
        } catch (Exception e) {
            e.printStackTrace();
            return new FebsResponse().fail().message("获取文件列表失败: " + e.getMessage());
        }
    }
 
    /**
     * 删除文件
     */
    @PostMapping("/delete")
    public FebsResponse deleteFile(@RequestParam("fileName") String fileName) {
        try {
            Path filePath = Paths.get(uploadDir, fileName);
            if (Files.exists(filePath)) {
                Files.delete(filePath);
            }
            return new FebsResponse().success().message("文件删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new FebsResponse().fail().message("文件删除失败: " + e.getMessage());
        }
    }
 
    /**
     * 保存文件信息
     */
    private void saveFileInfo(String fileName, long fileSize) {
        // 这里可以实现保存文件信息到数据库的逻辑
        // 简化处理,暂时不做数据库操作
    }
 
    /**
     * 文件信息实体类
     */
    public static class FileInfo {
        private String fileName;
        private long fileSize;
        private String uploadTime;
 
        public String getFileName() {
            return fileName;
        }
 
        public void setFileName(String fileName) {
            this.fileName = fileName;
        }
 
        public long getFileSize() {
            return fileSize;
        }
 
        public void setFileSize(long fileSize) {
            this.fileSize = fileSize;
        }
 
        public String getUploadTime() {
            return uploadTime;
        }
 
        public void setUploadTime(String uploadTime) {
            this.uploadTime = uploadTime;
        }
    }
}