使用 AWS SDK 中的 TransferManager
类上传文件时,可能会出现间歇性的失败。这种情况通常是因为网络连接或其他问题导致的。以下是一个解决方法的示例代码:
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.Upload;
import com.amazonaws.services.s3.transfer.model.UploadResult;
public class UploadFile {
public static void main(String[] args) {
String bucketName = "your-bucket-name";
String keyName = "your-file-key";
String filePath = "your-file-path";
AWSCredentials credentials = null;
try {
credentials = new ProfileCredentialsProvider().getCredentials();
} catch (Exception e) {
throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
+ "Please make sure that your credentials file is at the correct "
+ "location (~/.aws/credentials), and is in valid format.", e);
}
TransferManager transferManager = TransferManagerBuilder.standard()
.withS3Client(new AmazonS3Client(credentials))
.build();
Upload upload = transferManager.upload(bucketName, keyName, new File(filePath));
try {
UploadResult result = upload.waitForUploadResult();
System.out.println("Upload complete. Etag: " + result.getETag());
} catch (AmazonServiceException e) {
System.err.println(e.getErrorMessage());
System.exit(1);
} catch (InterruptedException e) {
System.err.println("Upload interrupted");
System.exit(1);
}
transferManager.shutdownNow();
}
}
在这个示例代码中,首先创建了一个 TransferManager
实例,用来管理上传操作。然后使用 upload
方法上传文件,并使用 waitForUploadResult
方法等待上传完成。如果上传过程中出现异常,可以使用 AmazonServiceException
来捕获并处理异常。
请确保替换示例代码中的以下变量值:
your-bucket-name
:要上传文件的 S3 存储桶名称your-file-key
:要上传文件的 S3 对象键your-file-path
:要上传的文件的本地路径此外,还需要设置正确的 AWS 认证凭据,可以通过配置 ~/.aws/credentials
文件或其他方式进行设置。