这是我写的通过carrierwave从ios应用程序上传到s3的内容:
首先是照片模型
class Photo
include Mongoid::Document
include Mongoid::Timestamps
mount_uploader :image, PhotoImageUploader
field :title, :type => String
field :description, :type => String
end
第二个在 Api::V1::PhotosController
def create
@photo = current_user.photos.build(params)
if @photo.save
render :json => @photo.to_json, :status=>201
else
render :json => {:errors => @photo.errors}.to_json, :status=>403
end
end
然后使用AFNetworking从我的 iPhone 应用程序调用
-(void) sendNewPhoto
{
NSURL *url = [NSURL URLWithString:@"http://myserverurl.com"];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:_photoTitle.text, @"title", _photoDescription.text, @"description",nil];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSString *endUrl = [NSString stringWithFormat:@"/api/v1/photos?auth_token=%@", [[User sharedInstance] token]];
NSData *imageData = UIImageJPEGRepresentation(_photo.image, 1.0);
NSURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:endUrl parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:@"image" fileName:@"image.jpg" mimeType:@"image/jpg"];
}];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"%@", JSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"Error creating photo!");
NSLog(@"%@", error);
}];
[operation start];
}
在 JSON 响应中,我可以获得 Photo 的新实例,其中 image.url 属性设置为 s3 中的 url。