728x90
반응형
2023.05.22 - [JavaScript/Node] - [Node.js] AWS S3에 presigned Url을 받아 업로드하기
[Node.js] AWS S3에 presigned Url을 받아 업로드하기
아직 s3 버킷을 만들지 않았다면 만들고 오세요! 2023.05.22 - [AWS] - [S3] S3란? 버킷 생성 후 정책 설정하기 [S3] S3란? 버킷 생성 후 정책 설정하기 S3 (Simple Storage Service) AWS S3는 업계 최고의 확장성과 데
kimwonny.tistory.com
이전에 Node.js 버전을 업로드했는데, springboot 에서는 아래와 같이 작성했다.
일단 스프링과 S3를 연동한다.
의존성 추가
implementation 'org.springframework.cloud:spring-cloud-starter-aws:2.2.6.RELEASE'
application.properties
spring.servlet.multipart.max-file-size=5MB
cloud.aws.stack.auto=false
cloud.aws.region.static=ap-northeast-2
cloud.aws.credentials.access-key=${AWS_ACCESS_KEY}
cloud.aws.credentials.secret-key=${AWS_SECRET_KEY}
cloud.aws.s3.bucket=${AWS_S3_BUCKET}
- 해당 IAM 계정의 accesskey와 secretkey 를 적어주고, s3 버킷 이름을 적어준다.
S3Config 생성
@Configuration
public class S3Config {
@Value("${cloud.aws.credentials.access-key}")
private String accessKey;
@Value("${cloud.aws.credentials.secret-key}")
private String secretKey;
@Value("${cloud.aws.region.static}")
private String region;
@Bean
public AmazonS3Client amazonS3Client() {
BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKey,secretKey);
return (AmazonS3Client) AmazonS3ClientBuilder.standard()
.withRegion(region)
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
.build();
}
}
Controller
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class Controller {
private final S3Service s3Service;
@GetMapping("/s3")
public Map<String, Serializable> s3saveImage(@RequestParam("fileName") String fileName){
return s3Service.getPreSignedUrl(fileName);
}
Service
@Service
@RequiredArgsConstructor
public class S3Service {
private final S3Config s3Config;
@Value("${cloud.aws.s3.bucket}")
private String bucket;
public Map<String, Serializable> getPreSignedUrl(String fileName) {
String encodedFileName = LocalDateTime.now() + "_" + fileName;
String objectKey = "test/" + encodedFileName;
Date expiration = new Date();
long expTimeMillis = expiration.getTime();
expTimeMillis += (3 * 60 * 1000); // 3 minutes
expiration.setTime(expTimeMillis); // Set URL expiration time
GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucket, objectKey)
.withMethod(HttpMethod.PUT)
.withExpiration(expiration);
Map<String, Serializable> result = new HashMap<>();
result.put("preSignedUrl", s3Config.amazonS3Client().generatePresignedUrl(generatePresignedUrlRequest));
result.put("encodedFileName", encodedFileName);
return result;
}
}
- url의 유효시간은 3분으로 설정 했다.
- test 폴더에 현재 시간을 붙여 파일을 업로드한다.
Vue
<template>
<input type="file" @change="uploadFile" ref="file">
</template>
<script>
data: {
return() {
file: null,
preSignedUrl: null,
encodedFileName: null,
uploadedUrl: null
}
}
methods: {
// S3 presigned url 받아오기
async uploadFile() {
this.file = this.$refs.file.files[0];
await axios.get("/api/s3", {params: {fileName: this.file.name}},)
.then((res) => {
console.log(res.data);
this.preSignedUrl = res.data.preSignedUrl
this.encodedFileName = res.data.encodedFileName
this.uploadImageToS3(this.preSignedUrl, this.file)
})
},
// S3 업로드
uploadImageToS3(preSignedUrl, file) {
axios.put(preSignedUrl, file)
.then(() => {
this.uploadedUrl = `${process.env.VUE_APP_S3_PATH} + this.encodedFileName`
});
},
}
</script>
- presigned url 을 받아와서 S3에 put 해준다!
- 오류가 난다면 S3 정책에서 PutObject 추가해줬는 지 확인할 것
728x90
반응형
'공개 > Spring' 카테고리의 다른 글
Swagger 접속시 오류 (0) | 2023.07.12 |
---|---|
[Springboot] CORS 설정시 Mapping 관련 오류 (0) | 2023.05.23 |
[SpringBoot] FormData로 받은 이미지 로컬에 저장하기 (0) | 2023.05.21 |
[Spring] @RequestMapping 과 상세 어노테이션 (0) | 2023.02.08 |
[SpringBoot] JPA, Hibernate, Spring Data JPA 차이점 (0) | 2023.01.10 |