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
| func (h *FileHandler) ChunkUpload(c *gin.Context) { zap.L().Info("上传分片请求开始", zap.String("url", c.Request.RequestURI), zap.String("method", c.Request.Method), zap.String("client_ip", c.ClientIP())) userID := c.GetInt("user_id") file, err := c.FormFile("chunk") if err != nil { zap.S().Errorf("无分片文件: %v", err) util.Error(c, 400, "无分片文件") return } chunkIndexStr := c.PostForm("chunk_index") chunkTotalStr := c.PostForm("chunk_total") fileHash := c.PostForm("file_hash") fileName := c.PostForm("file_name") fileMimeType := c.PostForm("file_mime_type") if chunkIndexStr == "" || chunkTotalStr == "" || fileHash == "" || fileName == "" { zap.S().Errorf("无分片元数据: %v", err) util.Error(c, 400, "请上传元数据") return } chunkIndex, err := strconv.Atoi(chunkIndexStr) if err != nil { zap.S().Errorf("不正确的chunkIndex格式: %v", err) util.Error(c, 400, "chunkIndex应当是数字") return } chunkTotal, err := strconv.Atoi(chunkTotalStr) if err != nil { zap.S().Errorf("不正确的chunkTotal格式: %v", err) util.Error(c, 400, "chunkTotal应当是数字") return }
if chunkIndex < 0 || chunkTotal < 1 { zap.S().Errorf("不正确的chunkIndex或chunkTotal: %v", err) util.Error(c, 400, "chunkIndex或chunkTotal错误") }
fileReader, err := file.Open() if err != nil { zap.S().Errorf("打开分片文件: %v", err) util.Error(c, 500, "打开分片文件失败") return } defer fileReader.Close()
chunkData := make([]byte, file.Size) _, err = fileReader.Read(chunkData) if err != nil { zap.S().Errorf("读取分片文件失败: %v", err) util.Error(c, 500, "读取分片文件失败") return }
if chunkIndex == 0 { err := h.fileService.InitChunkUpload(userID, fileName, fileHash, chunkTotal) if err != nil { zap.S().Errorf("初始化上传失败: %v", err) util.Error(c, 500, "初始化上传失败") return } }
err = h.fileService.SaveChunk(fileHash, userID, chunkIndex, chunkData) if err != nil { zap.S().Errorf("保存分片文件失败: %v", err) util.Error(c, 500, err.Error()) return }
if chunkIndex == chunkTotal-1 { file, err := h.fileService.MergeAllChunks(userID, fileHash, fileName, fileMimeType) if err != nil { zap.S().Errorf("合并分片失败: %v", err) util.Error(c, 500, "合并分片失败") return }
zap.L().Info("上传分片请求结束", zap.String("url", c.Request.RequestURI), zap.String("method", c.Request.Method), zap.String("client_ip", c.ClientIP()))
util.Success(c, gin.H{ "id": file.ID, "name": file.Name, "size": file.Size, "mime_type": file.MimeType, "created_at": file.CreatedAt, }, "文件上传成功") return }
zap.L().Info("上传分片请求结束", zap.String("url", c.Request.RequestURI), zap.String("method", c.Request.Method), zap.String("client_ip", c.ClientIP()))
util.Success(c, gin.H{ "chunk_index": chunkIndex, "chunk_total": chunkTotal, "status": "uncompleted", }, "分片上传成功") }
func (s *FileService) InitChunkUpload(userID int, fileName string, fileHash string, chunkTotal int) error { _, err := s.FileRepo.FindByHash(context.Background(), fileHash) if err == nil { return fmt.Errorf("文件已存在") }
err = s.FileRepo.InitChunkUploadSession(fileHash, chunkTotal) if err != nil { return fmt.Errorf("初始化缓存失败: %v", err) }
tmpPath := filepath.Join(".", s.uploadDir, fmt.Sprintf("user_%d", uint(userID)), "tmp_uploads/", fileHash) err = os.MkdirAll(tmpPath, 0755) if err != nil { s.FileRepo.CleanChunkUploadSession(fileHash) return fmt.Errorf("创建临时目录失败: %v", err) }
return nil }
func (s *FileService) SaveChunk(fileHash string, userID int, chunkIndex int, chunkData []byte) error { err := s.FileRepo.CheckChunkUploadSession(fileHash) if err != nil { if err.Error() == "redis: nil" { return errors.New("上传会话已过期,请重新上传") } return fmt.Errorf("访问缓存失败: %v", err) }
tmpPath := filepath.Join(s.uploadDir, fmt.Sprintf("user_%d", uint(userID)), "tmp_uploads/", fileHash) chunkPath := filepath.Join("."+tmpPath, fmt.Sprintf("chunk_%d", chunkIndex))
zap.S().Info(chunkPath) err = os.WriteFile(chunkPath, chunkData, 0644) if err != nil { return fmt.Errorf("保存分片失败: %v", err) }
err = s.FileRepo.UpdateChunkUploadSession(fileHash, chunkIndex) if err != nil { os.Remove(chunkPath) return fmt.Errorf("更新分片状态失败: %v", err) }
return nil }
func (s *FileService) MergeAllChunks(userID int, fileHash string, fileName string, mimetype string) (*model.File, error) { finished, err := s.FileRepo.IsChunkUploadFinished(fileHash) if err != nil { return &model.File{}, fmt.Errorf("检查上传状态失败: %v", err) } if !finished { return &model.File{}, fmt.Errorf("已上传的分片不完整") }
chunks, err := s.FileRepo.GetChunks(fileHash) if err != nil { return &model.File{}, fmt.Errorf("获取分片列表失败: %v", err) }
sort.Ints(chunks)
filePath, fileSize, _, err := s.MergeChunks(userID, fileHash, fileName, chunks) if err != nil { return &model.File{}, fmt.Errorf("合并分片失败: %v", err) }
s.FileRepo.CleanChunkUploadSession(fileHash)
ext := filepath.Ext(fileName) ext = ext[1:] file := model.File{ UserID: uint(userID), Name: fileName, Filename: s.CreateName(fileName, uint(userID)), Path: filePath, Size: fileSize, Hash: fileHash, MimeType: mimetype, Ext: ext, }
err = s.FileRepo.Create(context.Background(), &file) if err != nil { return &model.File{}, fmt.Errorf("上传文件失败: %v", err) }
return &file, nil }
func (s *FileService) MergeChunks(userID int, fileHash string, filename string, chunks []int) (string, int64, string, error) { fileName := s.CreateName(filename, uint(userID)) filePath := filepath.Join(s.uploadDir, fmt.Sprintf("user_%d", uint(userID)), fileName) ext := filepath.Ext(filePath) dir := filepath.Dir(filePath) if err := os.MkdirAll(dir, 0755); err != nil { return "", -1, "", err } finalFile, err := os.Create(filePath) if err != nil { return "", -1, "", errors.New("创建最终文件失败: %v" + err.Error()) } defer finalFile.Close()
var totalSize int64 tmpPath := filepath.Join(".", s.uploadDir, fmt.Sprintf("user_%d", uint(userID)), "tmp_uploads/", fileHash) for _, chunkIndex := range chunks { chunkPath := filepath.Join(tmpPath, fmt.Sprintf("chunk_%d", chunkIndex))
chunkFile, err := os.Open(chunkPath) if err != nil { return "", -1, "", errors.New("打开分片失败: %v" + err.Error()) }
writer, err := io.Copy(finalFile, chunkFile) chunkFile.Close() if err != nil { return "", -1, "", errors.New("合并分片失败: %v" + err.Error()) }
totalSize += writer
os.Remove(chunkPath) }
finalFileData, err := io.ReadAll(finalFile) if err != nil { return "", -1, "", errors.New("读取合并文件失败") }
if err := s.minioClient.Save(context.Background(), filePath, finalFileData, ext); err != nil { return "", -1, "", err }
os.Remove(tmpPath)
return filePath, totalSize, ext, nil }
|