PhotoGallery/src/main/java/com/example/PhotoGallery/Controller/ImageController.java

57 lines
1.9 KiB
Java

package com.example.PhotoGallery.Controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.nio.file.*;
@RestController
public class ImageController {
@Value("${photogallery.paths.thumbnails}")
private String thumbnailsPath;
@Value("${photogallery.paths.originals}")
private String originalsPath;
@GetMapping("/thumbnails/{filename:.+}")
public ResponseEntity<Resource> getThumbnail(@PathVariable String filename) {
return serveFile(thumbnailsPath, filename);
}
@GetMapping("/images/{filename:.+}")
public ResponseEntity<Resource> getFullImage(@PathVariable String filename) {
return serveFile(originalsPath, filename);
}
private ResponseEntity<Resource> serveFile(String baseDir, String filename) {
try {
Path basePath = Paths.get(baseDir).toAbsolutePath().normalize();
Path file = basePath.resolve(filename).normalize();
// Prevent path traversal
if (!file.startsWith(basePath)) {
return ResponseEntity.badRequest().build();
}
Resource resource = new UrlResource(file.toUri());
if (resource.exists() && resource.isReadable()) {
String contentType = Files.probeContentType(file);
if (contentType == null) {
contentType = "application/octet-stream";
}
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(contentType))
.body(resource);
}
} catch (Exception e) {
// Log exception if needed
}
return ResponseEntity.notFound().build();
}
}