우당탕탕 개발일지
59일차_클라우드 버킷에 이미지 저장 본문
반응형
1. Bucket 생성
bucket 생성
폴더 생성: storage
2. Amazon 서버 사용을 위한 환경 세팅
1. jar 파일 다운로드
AmazonS3를 사용하기 위해 다운로드 받은 jar 파일
2. Java 환경 설정
3. NCP에 파일 업로드
1. Java
NCPObjectStorageService.java
// NCP에 파일 업로드
public void uploadFile(File file, String bucketName, String directoryPath) {
String fileName = file.getName();
FileInputStream fileInput = null;
try {
fileInput = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// [파일 설정]
// 1. 파일 정보 변수
ObjectMetadata omdata = new ObjectMetadata(); // ObjectMetadata 클래스: 파일 정보를 설정할 수 있음.
Path path = Paths.get(file.getAbsolutePath()); // 파일 절대 경로
String contentType = null; // 파일 형태
try {
contentType = Files.probeContentType(path); // 파일 형태 가져오기
} catch (IOException e) {
e.printStackTrace();
}
// 2. 파일 정보 설정
omdata.setContentType(contentType); // 파일 형태 설정
omdata.setContentLength(file.length()); // 파일 크기 설정
PutObjectRequest putRequest = new PutObjectRequest(
bucketName,
directoryPath + fileName,
fileInput,
omdata
).withCannedAcl(CannedAccessControlList.PublicRead); // 리소스 접근 권한
// PublicRead : 모둔 사용자가 객체 일기 가능 But 수정/삭제 불가능
// 3. 파일 업로드
s3.putObject(putRequest);
}
2. 동작
웹에서 파일 업로드
NCP Bucket에 파일 업로드 된 것을 알 수 있음!
img 태그의 src 속성 값을 이미지 url로 지정
<tr>
<td class="no"><input class="itemNo" type="checkbox"> ${imageboardDTO.getSeq() }</td>
<!-- src="가상폴더의 위치" -->
<td class="image"><img height="150px" alt="" src="https://kr.object.ncloudstorage.com/bitcamp-9th-bucket-129/storage/${imageboardDTO.getImage1() }"> </td>
<td class="imageName"><a class="subjectA" href="#">${imageboardDTO.getImageName() }</a></td>
<td class="imagePrice"><fmt:formatNumber pattern="#,###" type="number" value="${imageboardDTO.getImagePrice() }" /></td>
<td class="imageQty"><fmt:formatNumber pattern="#,###" type="number" value="${imageboardDTO.getImageQty() }" /></td>
<td class="sum"><fmt:formatNumber pattern="#,###" type="number" value="${imageboardDTO.getImagePrice() * imageboardDTO.getImageQty() }" /></td>
</tr>
DB에는 3개의 목록이 있지만 NCP 클라우드에 업로드되어 있는 이미지만 확인 가능
img 태그의 src 속성 값에 이미지 url로 지정했기에 때문
3. 이미지 파일명 숫자 형태
1. Java
UUID 클래스를 사용하여 이미지 파일명을 숫자 형식으로 변환
2. 동작
3. NCP
기존에 있던 사과.jpg 파일을 올렸지만, 숫자형식으로 이름을 변경하였기에 숫자 형식으로 업로드됨
4. DB
DB 상에는 업로드한 파일명을 저장하였기에 사과.jpg로 저장됨
반응형
'비트캠프 > 이론 및 정리' 카테고리의 다른 글
61일차_DI (Dependency Injection) (1) | 2024.10.01 |
---|---|
60일_Spring Framwork (0) | 2024.09.30 |
58일차_Naver Cloud (0) | 2024.09.25 |
57일차_삭제 (0) | 2024.09.24 |
56일차_이미지 파일 업로드 (0) | 2024.09.23 |