これが私がiOSアプリケーションからcarrierwaveを介して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の2番目
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応答では、image.url属性がs3のurlに設定されたPhotoの新しいインスタンスを取得できます。