fixed controllers
This commit is contained in:
@@ -2,15 +2,18 @@ package com.krylov.refound.controller;
|
||||
|
||||
import com.krylov.refound.service.FileStorageService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.util.UriUtils;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/files")
|
||||
@RequiredArgsConstructor
|
||||
@@ -19,26 +22,21 @@ public class FileStorageController {
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
|
||||
log.info("uploadFile");
|
||||
String objectName = fileStorageService.uploadFile(file);
|
||||
return ResponseEntity.ok(objectName); // фронт сохранит objectName как ключ картинки
|
||||
}
|
||||
|
||||
@GetMapping("/{objectName}")
|
||||
@GetMapping("/{*objectName}")
|
||||
public ResponseEntity<byte[]> downloadFile(@PathVariable String objectName) {
|
||||
FileStorageService.DownloadedFile downloadedFile = fileStorageService.downloadFile(objectName);
|
||||
|
||||
String encodedFilename = UriUtils.encode(downloadedFile.originalFilename(), StandardCharsets.UTF_8);
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFilename);
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.headers(headers)
|
||||
.contentType(MediaType.parseMediaType(downloadedFile.contentType()))
|
||||
.body(downloadedFile.content());
|
||||
// objectName придёт как "/avatars/cf80aebe-...jpg" — обрежь ведущий слэш
|
||||
String key = objectName.startsWith("/") ? objectName.substring(1) : objectName;
|
||||
return fileStorageService.downloadFile(key);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{objectName}")
|
||||
public ResponseEntity<Void> deleteFile(@PathVariable String objectName) {
|
||||
log.info("deleteFile {}", objectName);
|
||||
fileStorageService.deleteFile(objectName);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user