如何在iOS中使用AWS S3服务上传文件, 我想将所选文件上传到AWS S3存储桶。
答案 0 :(得分:0)
此代码可帮助您解决问题
以下是在S3服务器上上传图片的示例代码
第1步 - 使用S3密钥和S3密钥初始化AWS S3配置
AWSStaticCredentialsProvider *credentialsProvider = [[AWSStaticCredentialsProvider alloc]initWithAccessKey:S3_KEY secretKey:S3_SECRET];
AWSServiceConfiguration *configuration = [[AWSServiceConfiguration alloc] initWithRegion:AWSRegionUSEast1 credentialsProvider:credentialsProvider];
第2步: - 上传文件/图像
if ([localReachability isReachable]) {
AWSS3TransferUtility *transferUtility = [AWSS3TransferUtility defaultS3TransferUtility];
AWSS3TransferUtilityUploadCompletionHandlerBlock completionHandler = ^(AWSS3TransferUtilityUploadTask *task, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
MLog(@"Image Upload Completion handler ");
if (!error) {
MLog(@"Image is uploaded successfully ");
[self imageUploadDidFinish];
}
else {
MLog(@"Image is failed to upload");
MLog(@"Error ::: %@",error);
[self imageUploadDidFail];
}
});
};
[[transferUtility uploadData:fileToUpload bucket:S3_BUCKET key:uploadPath contentType:@"image/jpg" expression:nil completionHander:completionHandler] continueWithBlock:^id(AWSTask *task) {
if (task.error) {
NSLog(@"Error: %@", task.error);
AWSS3TransferUtilityUploadTask *uploadTask = task.result;
[uploadTask cancel];
}
if (task.result) {
AWSS3TransferUtilityUploadTask *uploadTask = task.result;
MLog(@"uploadTask result :: %@",uploadTask);
}
return nil;
}];}
API参考: http://docs.aws.amazon.com/mobile/sdkforios/developerguide/s3transfermanager.html