@@ -0,0 +1,64 @@
|
||||
package ru.soune.nocopy.controller;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import ru.soune.nocopy.entity.file.FileEntity;
|
||||
import ru.soune.nocopy.repository.FileEntityRepository;
|
||||
import ru.soune.nocopy.service.file.FileStorageService;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/files")
|
||||
@Slf4j
|
||||
public class FileController {
|
||||
|
||||
@Autowired
|
||||
private FileStorageService fileStorageService;
|
||||
|
||||
@Autowired
|
||||
private FileEntityRepository fileRepository;
|
||||
|
||||
@GetMapping("/public/{fileId}")
|
||||
public ResponseEntity<Resource> getPublicFile(
|
||||
@PathVariable String fileId) throws IOException {
|
||||
|
||||
FileEntity fileEntity = fileRepository.findById(fileId)
|
||||
.orElseThrow(() -> new RuntimeException("File not found"));
|
||||
|
||||
// if (fileEntity.getProtectionStatus() != ProtectionStatus.NOT_PROTECTED) {
|
||||
// throw new RuntimeException("File is protected");
|
||||
// }
|
||||
|
||||
Resource resource = fileStorageService.loadFileAsResource(fileEntity.getFilePath());
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.contentType(new MediaType(fileEntity.getMimeType(), fileEntity.getFileExtension()))
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION,
|
||||
"inline; filename=\"" + fileEntity.getOriginalFileName() + "\"")
|
||||
.body(resource);
|
||||
}
|
||||
|
||||
@GetMapping("/download/{fileId}")
|
||||
public ResponseEntity<Resource> downloadFile(@PathVariable String fileId) throws IOException {
|
||||
|
||||
FileEntity fileEntity = fileRepository.findById(fileId)
|
||||
.orElseThrow(() -> new RuntimeException("File not found"));
|
||||
|
||||
Resource resource = fileStorageService.loadFileAsResource(fileEntity.getFilePath());
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION,
|
||||
"attachment; filename=\"" + fileEntity.getOriginalFileName() + "\"")
|
||||
.body(resource);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user