如何使用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找到感兴趣的示例项目.

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

  1. por.cannedACL = [S3CannedACL publicRead];

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

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

  1. NSString *uuid = @""; // Generate a UUID however you like,or use something else to name your image.
  2. UIImage *image; // This is the UIImage you'd like to upload.
  3.  
  4. // This URL is not used in the example,but it points to the file
  5. // to be uploaded.
  6. NSString *url = [NSString pathWithComponents:@[ @"https://s3.amazonaws.com/",AWS_PICTURE_BUCKET,uuid ]];
  7.  
  8. // Convert the image to JPEG data. Use UIImagePNGRepresentation for pngs
  9. NSData *imageData = UIImageJPEGRepresentation(image,1.0);
  10.  
  11. // Create the S3 Client.
  12. AmazonS3Client *s3 = [[AmazonS3Client alloc] initWithAccessKey:AWS_ACCESS_KEY_ID withSecretKey:AWS_SECRET_KEY];
  13.  
  14. @try {
  15. // Create the picture bucket.
  16. [s3 createBucket:[[S3CreateBucketRequest alloc] initWithName:AWS_PICTURE_BUCKET]];
  17.  
  18. // Upload image data. Remember to set the content type.
  19. S3PutObjectRequest *por = [[S3PutObjectRequest alloc] initWithKey:uuid inBucket:AWS_PICTURE_BUCKET];
  20. por.contentType = @"image/jpeg"; // use "image/png" here if you are uploading a png
  21. por.cannedACL = [S3CannedACL publicRead];
  22. por.data = imageData;
  23. por.delegate = self; // Don't need this line if you don't care about hearing a response.
  24.  
  25. // Put the image data into the specified s3 bucket and object.
  26. [s3 putObject:por];
  27. }
  28. @catch (AmazonClientException *exception) {
  29. NSLog(@"exception");
  30. }

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

猜你在找的iOS相关文章