![[GCP] SpringBoot에서 GCS에 오디오 파일 저장하기(2)](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2Frb4cF%2FbtsEXuBIMzp%2FFZ6yPriUQlSU53rWLOL7iK%2Fimg.png)
[GCP] SpringBoot에서 GCS에 오디오 파일 저장하기(2)GCP2024. 2. 18. 19:59
Table of Contents
https://kyko.tistory.com/44 다음 내용입니다.
프로젝트 세팅
1. json키 프로젝트에 추가
생성한 Json 키를 resources에 추가해 줍니다.
2. build.gradle 추가
// Google Storage
implementation group: 'org.springframework.cloud', name: 'spring-cloud-gcp-starter', version: '1.2.5.RELEASE'
implementation group: 'org.springframework.cloud', name: 'spring-cloud-gcp-storage', version: '1.2.5.RELEASE'
3. yml 파일 수정
spring:
cloud:
gcp:
storage:
credentials:
location: classpath:{json key 파일 이름}
project-id: {json key 파일 안에 있는 project_id 값}
bucket: {생성한 버킷 이름}
코드 작성
예시 코드는 일기 저장 코드입니다. 저장하기 위해 필요한 값은 일기 내용(content)과 오디오 파일입니다. 여기서 오디오 파일은 업로드하여 Google Storage에서 관리하고자 합니다. (오디오 파일 위주로만 참고하시면 됩니다!!)
1. Dto
@Getter
@Setter
@NoArgsConstructor
public class DiarySaveRequestDto {
private String content;
public Diary toEntity(String content, String audioFileUrl) {
return Diary.builder()
.content(content)
.audioFileUrl(audioFileUrl)
.status(DiaryStatus.CREATED)
.build();
}
}
2. Controller
@PostMapping(value = "/diaries")
public ResponseDto<Long> save(@RequestParam(value = "audioFile") MultipartFile audioFile,
DiarySaveRequestDto requestDto) {
Long diaryId = diaryService.save(audioFile, requestDto);
if (diaryId == 0) {
return ResponseUtil.FAILURE("일기 저장에 실패하였습니다.", 0L);
}
return ResponseUtil.SUCCESS("일기 저장에 성공하였습니다.", diaryId);
}
3. Service
@Value("${spring.cloud.gcp.storage.bucket}")
private String bucketName;
@Value("${spring.cloud.gcp.storage.project-id}")
private String projectId;
public Long save(MultipartFile audioFile, DiarySaveRequestDto requestDto) {
try {
//resources 파일을 위해 사용. 파일 경로를 scr/main/resources/ 부터 바로 읽을 수 있다.
ClassPathResource resource = new ClassPathResource("strecording-upload.json");
//Google Cloud Storage에 접근하기 위한 strecording-upload.json 파일을 참조
GoogleCredentials credentials = GoogleCredentials.fromStream(resource.getInputStream());
//Google Cloud Storage 서비스에 연결하기 위한 Storage 객체 생성
Storage storage = StorageOptions.newBuilder().setProjectId(projectId).setCredentials(credentials)
.build().getService();
//파일 이름은 중복되면 안되기에 uuid 생성
String uuid = UUID.randomUUID().toString();
//파일 확장자(파일 형식 flac)
String extension = audioFile.getContentType();
//Google Cloud Storage에 파일 업로드
BlobInfo blobInfo = storage.create(BlobInfo.newBuilder(bucketName, uuid).setContentType(extension).build(), audioFile.getBytes());
//저장된 파일 Url
String audioUrl = "https://storage.googleapis.com/" + bucketName + "/" + uuid;
Long diaryId = diaryRepository.save(requestDto.toEntity(requestDto.getContent(), audioUrl)).getId();
return diaryId;
} catch (IOException e) {
e.printStackTrace();
}
return 0L;
}
테스트
1. Postman으로 테스트 실행
2. DB 확인
3. GCP 확인
참고자료
Springboot에서 GCS로 이미지 파일 업로드 총정리(multipart/form-data)(Google Cloud Storage)(GCP)
1. 서론
choo.oopy.io
Uses of Class com.google.cloud.storage.BlobInfo (Google Cloud 0.116.0-alpha API)
Blob Storage.create(BlobInfo blobInfo, byte[] content, int offset, int length, Storage.BlobTargetOption... options) Creates a new blob with the sub array of the given byte array.
googleapis.dev
'GCP' 카테고리의 다른 글
[GCP] SpringBoot에서 GCS에 오디오 파일 저장하기(1) (1) | 2024.01.30 |
---|---|
[GCP] 구글 클라우드 플랫폼을 이용한 DB 생성 (0) | 2024.01.07 |
[GCP] 구글 클라우드 플랫폼을 이용한 웹 서버 구축 (0) | 2024.01.06 |
@Kyko :: Kyko dev_story
느리더라도 단단하게 성장하고자 합니다!
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!