1

我正在尝试将文件上传到 Amazon S3,没什么特别的。我已经设法进行实际上传,并且文件上传成功。剩下的唯一问题是我无法更改 S3 中的文件名。似乎默认情况下,文件名被设置为与密钥相同。可能是我将密钥作为参数发送,我应该在其中发送文件名。但是,我尝试更改参数并出现错误。

请在下面找到我正在使用的代码:

Bucket bucket = client.createBucket("testBucket", Region.EU_Ireland);

    List<PartETag> partTags = new ArrayList<>();

    InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(
            bucket.getName(), secretAmazonKey);

    InitiateMultipartUploadResult result = client
            .initiateMultipartUpload(request);
    File file = new File(filePath);
    long contentLength = file.length();
    long partSize = 8 * 1024 * 1024;

    try {
        // Uploading the file, part by part.
        long filePosition = 0;

        for (int i = 1; filePosition < contentLength; i++) {
            // Last part can be less than 8 MB therefore the partSize needs
            // to be adjusted accordingly
            partSize = Math.min(partSize, (contentLength - filePosition));

            // Creating the request for a part upload
            UploadPartRequest uploadRequest = new UploadPartRequest()
                    .withBucketName(bucket.getName()).withKey(secretAmazonKey)
                    .withUploadId(result.getUploadId()).withPartNumber(i)
                    .withFileOffset(filePosition).withFile(file)
                    .withPartSize(partSize);

            // Upload part and add response to the result list.
            partTags.add(client.uploadPart(uploadRequest).getPartETag());

            filePosition += partSize;
        }
    }

    catch (Exception e) {
        client.abortMultipartUpload(new AbortMultipartUploadRequest(bucket
                .getName(), secretAmazonKey, result.getUploadId()));
    }

    CompleteMultipartUploadRequest compRequest = new CompleteMultipartUploadRequest(
            bucket.getName(), secretAmazonKey, result.getUploadId(), partTags);

    client.completeMultipartUpload(compRequest);

任何帮助深表感谢。

非常感谢 :)

4

2 回答 2

4

您的key上传请求中的实际上是您的对象(文件)密钥(名称),而不是您的 AWS 密钥。每当您实例化您的client实例时,这就是您指定 AWS 凭证的时间。

您能否更具体地说明您在执行此操作时看到的错误?

于 2012-07-13T15:19:23.697 回答
-1

好吧,我最近第一次使用 Amazon S3 并且能够上传如下文件:

public void saveMinutes(Minutes minutes, byte [] data)
{

  AmazonS3 s3 = new AmazonS3Client(new BasicAWSCredentials(amazonS3AccessKey, amazonS3SecretAccessKey));
  ObjectMetadata metaData = new ObjectMetadata();
  metaData.setContentLength(data.length);
  metaData.setContentType("application/pdf");
  s3.putObject(new PutObjectRequest(amazonS3MinutesBucketName, minutes.getFileName(), new ByteArrayInputStream(data), metaData));
}
于 2012-07-13T15:26:45.943 回答