Amazon S3 업로드 파일 및 URL 가져 오기


답변:


-35

업로드하기 전에 파일을 공개하려면 다음 #withCannedAcl방법을 사용할 수 있습니다 PutObjectRequest.

myAmazonS3Client.putObject(new PutObjectRequest('some-grails-bucket',  'somePath/someKey.jpg', new    File('/Users/ben/Desktop/photo.jpg')).withCannedAcl(CannedAccessControlList.PublicRead))

46
이 요청에서 링크를 얻으려면 어떻게합니까?
— Andreas Rudolph

60
이것은 업로드 된 리소스의 공개 URL을 얻는 방법을 알려주지 않습니다.
— Valentin Waeselynck 2014 년

왜 이것이 허용되는 대답입니까?
— lanxion

107

아니요 한 번의 작업으로 URL을 얻을 수는 없지만 두 가지 :)

우선, 아무도 액세스 할 수없는 URL을 얻는 것이 이치에 맞지 않기 때문에 업로드하기 전에 파일을 공개해야 할 수 있습니다. Michael Astreiko가 제안한대로 ACL을 설정하면됩니다. getResourceUrl또는 을 호출하여 리소스 URL을 가져올 수 있습니다 getUrl.

AmazonS3Client s3Client = (AmazonS3Client)AmazonS3ClientBuilder.defaultClient();
s3Client.putObject(new PutObjectRequest("your-bucket", "some-path/some-key.jpg", new File("somePath/someKey.jpg")).withCannedAcl(CannedAccessControlList.PublicRead))
s3Client.getResourceUrl("your-bucket", "some-path/some-key.jpg");

주 : 서로 다른 사이 getResourceUrl및 getUrl예외가 발생했을 때 getResourceUrl가 null를 돌려주는 것입니다.

참고 2 : getUrl 메서드는 AmazonS3 인터페이스에 정의되어 있지 않습니다. 표준 빌더를 사용하는 경우 객체를 AmazonS3Client로 캐스팅해야합니다.


27
이로 인해 AWS에 대한 단일 호출 만 발생한다는 점은 주목할 가치가 있습니다. Java SDK를 자세히 살펴보면 s3Client.getResourceUrl("your-bucket", "some-path/some-key.jpg")AWS를 호출하지 않고도 URL 이 작동하는 것을 알 수 있습니다 .
— sihil

3
이것은 정말로 권장되는 대답이어야합니다. 다른 답변은 파일 이름에 공백이 포함 된 경우 실패합니다. 이러한 시나리오에서 S3에 표시되는 파일 이름과 URL 접미사는 서로 다릅니다. 위의 s3Client.getUrl 메서드는이 시나리오를 올바르게 처리합니다
— RvPr

3
참고, getResourceUrl최신 sdk에 없습니다.
— Martin Serrano

6
최신 sdk의 s3Client.getUrl("your-bucket", "some-path/some-key.jpg").toString();경우 공개 URL을 가져옵니다.
— kristianva

2
더 새로운 SDK 버전의 경우 다음을 시도하십시오s3Client.utilities().getUrl(getUrlRequest);
— mrog

84

업로드 요청에서 지정한 버킷과 파일 이름이 주어지면 스스로 해결할 수 있습니다.

예를 들어 버킷이 mybucket있고 파일 이름이 myfilename다음 과 같은 경우 :

https://mybucket.s3.amazonaws.com/myfilename

s3비트는 버킷에있는 지역에 따라 다를 수 있습니다 내 URL이 같은 그래서 예를 들어, 나는 동남아시아 영역을 사용합니다. :

https://mybucket.s3-ap-southeast-1.amazonaws.com/myfilename

AWS 관리 콘솔에서 파일을 업로드 한 후, 다음 링크는 하나가 응답 .. 될 수있는 그래서, 하나의 파일 작동 s3.amazonaws.com/cdn.generalsentiment.com/MVR/reports/... - cdn.generalsentiment. com.s3.amazonaws.com/MVR/reports/... - cdn.generalsentiment.com/MVR/reports/...
— Sangram 아난드

1
예, 작동해야하는 URL에 대한 변형이 있습니다. 사용하려는 것을 선택하고 함께 사용하십시오.
— Jeffrey Kemp

Kool .. 정보 주셔서 감사합니다 .. 그런데 업로드 부분은 AWS sdk 라이브러리와 관련이 있습니까?
— Sangram 아난드

네, 그렇게 믿습니다. 그러나 나는 스트럿에 대한 경험이 없습니다.
— Jeffrey Kemp

업로딩은 거의 다 끝났지 만 .. 권한에 충격을 받았습니다. S3 용 AWS Java SDK에 업로드하기 전에 파일을 공개 할 수있는 방법이 있습니까?
— Sangram Anand

6

@hussachai 및 @Jeffrey Kemp 답변은 꽤 좋습니다. 그러나 그들은 반환 된 URL이 경로 스타일이 아닌 가상 호스트 스타일이라는 공통점이 있습니다. s3 URL 스타일에 대한 자세한 내용은 AWS S3 URL 스타일을 참조하십시오 . 어떤 사람들은 경로 스타일 s3 URL을 생성하고 싶어합니다. 여기에 단계가 있습니다. 기본적으로 모든 것이 @hussachai 및 @Jeffrey Kemp 답변과 동일하며 아래와 같이 한 줄 설정 만 변경됩니다.

AmazonS3Client s3Client = (AmazonS3Client) AmazonS3ClientBuilder.standard()
                    .withRegion("us-west-2")
                    .withCredentials(DefaultAWSCredentialsProviderChain.getInstance())
                    .withPathStyleAccessEnabled(true)
                    .build();

// Upload a file as a new object with ContentType and title specified.
PutObjectRequest request = new PutObjectRequest(bucketName, stringObjKeyName, fileToUpload);
s3Client.putObject(request);
URL s3Url = s3Client.getUrl(bucketName, stringObjKeyName);
logger.info("S3 url is " + s3Url.toExternalForm());

다음과 같은 URL이 생성됩니다. https://s3.us-west-2.amazonaws.com/mybucket/myfilename


5

마찬가지로 s3Client를 통해 링크하려면 아래에서 사용할 수 있습니다.

System.out.println("filelink: " + s3Client.getUrl("your_bucket_name", "your_file_key"));

2

조금 오래되었지만 미래에 이것에 걸림돌이되는 사람에게는 여전히

CredentialProvider 및 AmazonS3Client를 이미 작성했다고 가정하고 한 줄로 수행 할 수 있습니다.

다음과 같이 보일 것입니다.

 String ImageURL = String.valueOf(s3.getUrl(
                                  ConstantsAWS3.BUCKET_NAME, //The S3 Bucket To Upload To
                                  file.getName())); //The key for the uploaded object

CredentialProvider 및 AmazonS3Client를 작성하지 않은 경우 다음과 같은 URL을 가져 오기 전에 추가하십시오.

  CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
        getApplicationContext(),
        "POOL_ID", // Identity pool ID
        Regions.US_EAST_1 // Region
);

1

AWS SDK 2 이상

String key = "filePath";
String bucketName = "bucketName";
PutObjectResponse response = s3Client
            .putObject(PutObjectRequest.builder().bucket(bucketName ).key(key).build(), RequestBody.fromFile(file));
 GetUrlRequest request = GetUrlRequest.builder().bucket(bucketName ).key(key).build();
 String url = s3Client.utilities().getUrl(request).toExternalForm();

0
        System.out.println("Link : " + s3Object.getObjectContent().getHttpRequest().getURI());

이를 통해 S3 버킷에 이미 업로드 된 파일의 링크를 검색 할 수 있습니다.


0

아래 메소드는 버킷의 특정 폴더에 파일을 업로드하고 업로드 된 파일의 생성 된 URL을 반환합니다.

private String uploadFileToS3Bucket(final String bucketName, final File file) {
    final String uniqueFileName = uploadFolder + "/" + file.getName();
    LOGGER.info("Uploading file with name= " + uniqueFileName);
    final PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, uniqueFileName, file);
    amazonS3.putObject(putObjectRequest);
    return ((AmazonS3Client) amazonS3).getResourceUrl(bucketName, uniqueFileName);
}
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.