如何使用AWS iOS SDK从设备上传图像并设置为公开

前端之家收集整理的这篇文章主要介绍了如何使用AWS iOS SDK从设备上传图像并设置为公开前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
由于看起来我们只限于桶数,我试图找出如何完成以下操作:

>我有一个iOS应用,用户可以上传一个个人资料图片.
>个人资料可以被任何人查看(我想要公开).
>理想情况下,我可以上传到一个桶(例如:myprofilepics.s3.amazonaws.com)
>理想情况下,每个用户都可以上传到自己的子文件夹(例如:myprofilepics.s3.amazonaws.com/images/userXXX/
>理想情况下,我上传图像,并将其设置为直接从应用程序访问公共访问,以便其他用户可以立即查看个人资料图片.

我在文档中缺少某些东西吗?我感谢任何关于这个问题的反馈.

解决方法

为了解决这个问题,我在Amazon SDK的iOS SDK中开始了一个示例代码,发现了 here.在SDK zip中,可以在样例/ S3_Uploader找到感兴趣的示例项目.

要从该示例项目到上传的图像公开的项目,您只需在正确的位置添加一行:

por.cannedACL   = [S3CannedACL publicRead];

其中por是用于上传图像的S3PutObjectRequest.

我的项目的上传代码看起来像这样(看起来几乎与Amazon的示例代码相同):

NSString *uuid = @""; // Generate a UUID however you like,or use something else to name your image.
UIImage *image; // This is the UIImage you'd like to upload.

// This URL is not used in the example,but it points to the file
// to be uploaded.
NSString *url = [NSString pathWithComponents:@[ @"https://s3.amazonaws.com/",AWS_PICTURE_BUCKET,uuid ]];

// Convert the image to JPEG data. Use UIImagePNGRepresentation for pngs
NSData *imageData = UIImageJPEGRepresentation(image,1.0);

// Create the S3 Client.
AmazonS3Client *s3 = [[AmazonS3Client alloc] initWithAccessKey:AWS_ACCESS_KEY_ID withSecretKey:AWS_SECRET_KEY];

@try {
    // Create the picture bucket.
    [s3 createBucket:[[S3CreateBucketRequest alloc] initWithName:AWS_PICTURE_BUCKET]];

    // Upload image data.  Remember to set the content type.
    S3PutObjectRequest *por = [[S3PutObjectRequest alloc] initWithKey:uuid inBucket:AWS_PICTURE_BUCKET];
    por.contentType = @"image/jpeg"; // use "image/png" here if you are uploading a png
    por.cannedACL   = [S3CannedACL publicRead];
    por.data        = imageData;
    por.delegate    = self; // Don't need this line if you don't care about hearing a response.

    // Put the image data into the specified s3 bucket and object.
    [s3 putObject:por];
}
@catch (AmazonClientException *exception) {
    NSLog(@"exception");
}

当然,AWS_ACCESS_KEY_ID和AWS_SECRET_KEY是您的AWS凭据,AWS_PICTURE_BUCKET是您的图片桶.

猜你在找的iOS相关文章