Merge pull request #44 from SlimusMinus/fix-get_image
All checks were successful
deploy-backend / deploy (push) Successful in 1m27s
All checks were successful
deploy-backend / deploy (push) Successful in 1m27s
fixed getting image from minio
This commit is contained in:
@@ -1,6 +1,8 @@
|
|||||||
package com.krylov.refound.controller;
|
package com.krylov.refound.controller;
|
||||||
|
|
||||||
import com.krylov.refound.service.FileStorageService;
|
import com.krylov.refound.service.FileStorageService;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.Map;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
@@ -34,6 +36,32 @@ public class FileStorageController {
|
|||||||
return fileStorageService.downloadFile(key);
|
return fileStorageService.downloadFile(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Редирект на presigned URL для прямой загрузки файла с MinIO (Вариант B).
|
||||||
|
* Браузер перейдёт по 302 на временную ссылку и скачает картинку напрямую с MinIO.
|
||||||
|
*/
|
||||||
|
@GetMapping(value = "/{*objectName}", params = "presigned=true")
|
||||||
|
public ResponseEntity<Void> redirectToPresigned(@PathVariable String objectName) {
|
||||||
|
String key = objectName.startsWith("/") ? objectName.substring(1) : objectName;
|
||||||
|
String url = fileStorageService.generatePresignedDownloadUrl(key, Duration.ofHours(24));
|
||||||
|
return ResponseEntity.status(302)
|
||||||
|
.header("Location", url)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Возвращает presigned URL в JSON.
|
||||||
|
* PathPatternParser не допускает ничего после {*...}, поэтому "url" вынесен в префикс:
|
||||||
|
* GET /api/v1/files/url/avatars/cf80aebe-...jpg?ttlHours=24
|
||||||
|
*/
|
||||||
|
@GetMapping("/url/{*objectName}")
|
||||||
|
public ResponseEntity<Map<String, String>> getPresignedUrl(@PathVariable String objectName, @RequestParam(value = "ttlHours", required = false, defaultValue = "24") long ttlHours) {
|
||||||
|
String key = objectName.startsWith("/") ? objectName.substring(1) : objectName;
|
||||||
|
Duration ttl = ttlHours > 0 ? Duration.ofHours(ttlHours) : Duration.ofHours(24);
|
||||||
|
String url = fileStorageService.generatePresignedDownloadUrl(key, ttl);
|
||||||
|
return ResponseEntity.ok(Map.of("url", url));
|
||||||
|
}
|
||||||
|
|
||||||
@DeleteMapping("/{*objectName}")
|
@DeleteMapping("/{*objectName}")
|
||||||
public ResponseEntity<Void> deleteFile(@PathVariable String objectName) {
|
public ResponseEntity<Void> deleteFile(@PathVariable String objectName) {
|
||||||
log.info("deleteFile {}", objectName);
|
log.info("deleteFile {}", objectName);
|
||||||
@@ -42,4 +70,4 @@ public class FileStorageController {
|
|||||||
fileStorageService.deleteFileAsCurrentUser(key);
|
fileStorageService.deleteFileAsCurrentUser(key);
|
||||||
return ResponseEntity.noContent().build();
|
return ResponseEntity.noContent().build();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -38,12 +38,15 @@ import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
|
|||||||
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
|
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
|
||||||
import software.amazon.awssdk.services.s3.model.S3Exception;
|
import software.amazon.awssdk.services.s3.model.S3Exception;
|
||||||
import software.amazon.awssdk.core.exception.SdkClientException;
|
import software.amazon.awssdk.core.exception.SdkClientException;
|
||||||
|
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
|
||||||
|
import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class FileStorageService {
|
public class FileStorageService {
|
||||||
private final S3Client s3Client;
|
private final S3Client s3Client;
|
||||||
|
private final S3Presigner s3Presigner;
|
||||||
private final MinioProperties properties;
|
private final MinioProperties properties;
|
||||||
private final StringRedisTemplate redisTemplate;
|
private final StringRedisTemplate redisTemplate;
|
||||||
|
|
||||||
@@ -126,6 +129,38 @@ public class FileStorageService {
|
|||||||
.body(file.content());
|
.body(file.content());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Генерирует presigned URL для скачивания файла напрямую из MinIO/S3.
|
||||||
|
* Браузер будет загружать картинку по этому URL, минуя backend (меньше нагрузки).
|
||||||
|
*/
|
||||||
|
public String generatePresignedDownloadUrl(String objectName, Duration ttl) {
|
||||||
|
try {
|
||||||
|
GetObjectRequest getRequest = GetObjectRequest.builder()
|
||||||
|
.bucket(properties.bucket())
|
||||||
|
.key(objectName)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
GetObjectPresignRequest presignRequest = GetObjectPresignRequest.builder()
|
||||||
|
.signatureDuration(ttl)
|
||||||
|
.getObjectRequest(getRequest)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
String url = s3Presigner.presignGetObject(presignRequest).url().toString();
|
||||||
|
log.debug("Сгенерирован presigned URL для файла '{}', TTL={}", objectName, ttl);
|
||||||
|
return url;
|
||||||
|
} catch (S3Exception | SdkClientException e) {
|
||||||
|
log.error("Ошибка при генерации presigned URL для файла '{}': {}", objectName, e.getMessage(), e);
|
||||||
|
throw new ApiException(ErrorCode.INTERNAL_ERROR, "Ошибка при формировании ссылки на файл.", HttpStatus.INTERNAL_SERVER_ERROR);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Генерирует presigned URL со стандартным TTL.
|
||||||
|
*/
|
||||||
|
public String generatePresignedDownloadUrl(String objectName) {
|
||||||
|
return generatePresignedDownloadUrl(objectName, Duration.ofHours(24));
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Скачивает файл из MinIO без HTTP-обёртки — оригинальное имя, content-type и байты.
|
* Скачивает файл из MinIO без HTTP-обёртки — оригинальное имя, content-type и байты.
|
||||||
* Используется там, где нет HTTP-контекста (например, в PostModerationScheduler,
|
* Используется там, где нет HTTP-контекста (например, в PostModerationScheduler,
|
||||||
|
|||||||
Reference in New Issue
Block a user