반응형
서비스 로직 생성
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@Service
public class ImageService {
private final ImageRepository imageRepository;
public ImageService(ImageRepository imageRepository) {
this.imageRepository = imageRepository;
}
public Image saveImage(MultipartFile file) throws IOException {
Image image = new Image();
image.setName(file.getOriginalFilename());
image.setContentType(file.getContentType());
image.setImageData(file.getBytes()); // 파일을 바이트 배열로 변환
return imageRepository.save(image);
}
public Image getImage(Long id) {
return imageRepository.findById(id).orElseThrow(() -> new RuntimeException("Image not found"));
}
}
컨트롤러 작성
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/images")
public class ImageController {
private final ImageService imageService;
public ImageController(ImageService imageService) {
this.imageService = imageService;
}
// 이미지 업로드
@PostMapping("/upload")
public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) {
try {
Image savedImage = imageService.saveImage(file);
return ResponseEntity.ok("Image uploaded successfully with ID: " + savedImage.getId());
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error uploading image");
}
}
// 이미지 다운로드
@GetMapping("/{id}")
public ResponseEntity<byte[]> getImage(@PathVariable Long id) {
Image image = imageService.getImage(id);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_TYPE, image.getContentType())
.body(image.getImageData());
}
}반응형
'SpringBoot (JAVA)' 카테고리의 다른 글
| Windows에서 NSSM과 Nginx로 안정적인 웹 서버 운영하기 (1) | 2025.08.18 |
|---|---|
| [SpringBoot] SpringBoot를 이용하여 MS-SQL에 사용자정의 테이블 이용하기 (0) | 2024.11.26 |
| SpringBoot 를 IIS에 배포하기 (0) | 2024.08.16 |
| NginX 를 이용한 무중단배포 (0) | 2024.08.16 |
| NSSM을 이용한 .jar 서비스 등록 (0) | 2023.07.19 |