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
|
@Service public class ChunkDownloadService {
@Autowired private FileRepository fileRepository;
@Autowired private RedisTemplate<String, Object> redisTemplate;
private final String CHUNK_DOWNLOAD_CACHE_PREFIX = "chunk_download:"; private final int CHUNK_SIZE = 1024 * 1024;
public ResponseEntity<Resource> downloadFileChunk(String fileId, Long start, Long end, HttpServletRequest request) { try { validateFileId(fileId);
validateChunkParameters(start, end);
Long userId = getCurrentUserId(request); checkUserPermission(userId, fileId);
FileInfo fileInfo = getFileInfo(fileId);
checkFileExists(fileInfo);
validateChunkRange(fileInfo, start, end);
Resource resource = buildChunkResource(fileInfo, start, end);
recordDownloadLog(fileId, userId, request, start, end);
HttpHeaders headers = buildChunkDownloadHeaders(fileInfo, start, end);
return ResponseEntity.ok() .headers(headers) .body(resource);
} catch (Exception e) { log.error("分片下载文件失败: {}", fileId, e); return ResponseEntity.notFound().build(); } }
private void validateChunkParameters(Long start, Long end) { if (start == null || start < 0) { throw new IllegalArgumentException("起始位置不能为空或小于0"); }
if (end == null || end < 0) { throw new IllegalArgumentException("结束位置不能为空或小于0"); }
if (start > end) { throw new IllegalArgumentException("起始位置不能大于结束位置"); }
if (end - start > CHUNK_SIZE) { throw new IllegalArgumentException("分片大小不能超过" + CHUNK_SIZE + "字节"); } }
private void validateChunkRange(FileInfo fileInfo, Long start, Long end) { if (start >= fileInfo.getFileSize()) { throw new IllegalArgumentException("起始位置超出文件大小"); }
if (end > fileInfo.getFileSize()) { throw new IllegalArgumentException("结束位置超出文件大小"); } }
private Resource buildChunkResource(FileInfo fileInfo, Long start, Long end) { try { Path filePath = Paths.get(fileInfo.getFilePath()); RandomAccessFile randomAccessFile = new RandomAccessFile(filePath.toFile(), "r");
randomAccessFile.seek(start);
long chunkSize = end - start + 1;
byte[] chunkData = new byte[(int) chunkSize]; randomAccessFile.read(chunkData); randomAccessFile.close();
ByteArrayResource resource = new ByteArrayResource(chunkData);
return resource;
} catch (Exception e) { log.error("构建分片资源失败", e); throw new IllegalArgumentException("构建分片资源失败"); } }
private HttpHeaders buildChunkDownloadHeaders(FileInfo fileInfo, Long start, Long end) { try { HttpHeaders headers = new HttpHeaders();
String contentType = Files.probeContentType(Paths.get(fileInfo.getFilePath())); if (contentType == null) { contentType = "application/octet-stream"; } headers.setContentType(MediaType.parseMediaType(contentType));
long chunkSize = end - start + 1; headers.setContentLength(chunkSize);
headers.set("Content-Range", "bytes " + start + "-" + end + "/" + fileInfo.getFileSize());
String fileName = URLEncoder.encode(fileInfo.getFileName(), StandardCharsets.UTF_8.toString()); headers.setContentDispositionFormData("attachment", fileName);
headers.setCacheControl(CacheControl.noCache().mustRevalidate());
return headers;
} catch (Exception e) { log.error("构建分片下载响应头失败", e); return new HttpHeaders(); } }
private void validateFileId(String fileId) { if (fileId == null || fileId.trim().isEmpty()) { throw new IllegalArgumentException("文件ID不能为空"); }
if (!fileId.matches("^[a-zA-Z0-9_-]+$")) { throw new IllegalArgumentException("文件ID格式不正确"); } }
private Long getCurrentUserId(HttpServletRequest request) { try { String token = request.getHeader("Authorization"); if (token == null || token.trim().isEmpty()) { throw new IllegalArgumentException("用户未登录"); }
return userService.getUserIdFromToken(token);
} catch (Exception e) { log.error("获取当前用户ID失败", e); throw new IllegalArgumentException("用户身份验证失败"); } }
private void checkUserPermission(Long userId, String fileId) { try { String cacheKey = CHUNK_DOWNLOAD_CACHE_PREFIX + "permission:" + fileId + ":" + userId; Boolean hasPermission = (Boolean) redisTemplate.opsForValue().get(cacheKey);
if (hasPermission != null) { if (!hasPermission) { throw new IllegalArgumentException("无权限下载此文件"); } return; }
boolean permission = fileRepository.checkUserPermission(fileId, userId);
redisTemplate.opsForValue().set(cacheKey, permission, Duration.ofSeconds(3600));
if (!permission) { throw new IllegalArgumentException("无权限下载此文件"); }
} catch (Exception e) { log.error("检查用户权限失败", e); throw new IllegalArgumentException("权限验证失败"); } }
private FileInfo getFileInfo(String fileId) { try { String cacheKey = CHUNK_DOWNLOAD_CACHE_PREFIX + "info:" + fileId; FileInfo fileInfo = (FileInfo) redisTemplate.opsForValue().get(cacheKey);
if (fileInfo != null) { return fileInfo; }
fileInfo = fileRepository.findByFileId(fileId); if (fileInfo == null) { throw new IllegalArgumentException("文件不存在"); }
redisTemplate.opsForValue().set(cacheKey, fileInfo, Duration.ofSeconds(3600));
return fileInfo;
} catch (Exception e) { log.error("获取文件信息失败", e); throw new IllegalArgumentException("获取文件信息失败"); } }
private void checkFileExists(FileInfo fileInfo) { try { Path filePath = Paths.get(fileInfo.getFilePath()); if (!Files.exists(filePath)) { throw new IllegalArgumentException("文件不存在"); }
if (!Files.isReadable(filePath)) { throw new IllegalArgumentException("文件不可读"); }
} catch (Exception e) { log.error("检查文件是否存在失败", e); throw new IllegalArgumentException("文件检查失败"); } }
private void recordDownloadLog(String fileId, Long userId, HttpServletRequest request, Long start, Long end) { try { DownloadLog downloadLog = new DownloadLog(); downloadLog.setFileId(fileId); downloadLog.setUserId(userId); downloadLog.setIpAddress(getClientIpAddress(request)); downloadLog.setUserAgent(request.getHeader("User-Agent")); downloadLog.setDownloadTime(LocalDateTime.now()); downloadLog.setChunkStart(start); downloadLog.setChunkEnd(end);
CompletableFuture.runAsync(() -> { try { fileRepository.saveDownloadLog(downloadLog); } catch (Exception e) { log.error("记录下载日志失败", e); } });
} catch (Exception e) { log.error("记录下载日志失败", e); } }
private String getClientIpAddress(HttpServletRequest request) { String xForwardedFor = request.getHeader("X-Forwarded-For"); if (xForwardedFor != null && !xForwardedFor.isEmpty()) { return xForwardedFor.split(",")[0].trim(); }
String xRealIp = request.getHeader("X-Real-IP"); if (xRealIp != null && !xRealIp.isEmpty()) { return xRealIp; }
return request.getRemoteAddr(); } }
|