0

I used this method to POST an image to server before, but it's a little complicated because I have to add header and boundary by myself. Yesterday I found a project called Resty - "A simple Objective-C HTTP client for iOS and Mac". However, after reading all of its documents, I can't find any method to upload an image file. Please help, thanks so much.

NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setObject:@"this is a title" forKey:@"title"];

// ***How can I add an image by Resty?***
[params setObject:UIImageJPEGRepresentation(self.image, 1.0) forKey:@"image"];

LRRestyClient *client = [LRResty client];
[client setUsername:userId password:userToken];
[client post:APIImageUrl payload:params withBlock:^(LRRestyResponse *response){
    NSLog(@"Done");
}];
Community
  • 1
  • 1
iForests
  • 6,757
  • 10
  • 42
  • 75

2 Answers2

0

i think this framework not handle image data and custom parameters correctly you may follow this topic and create correct NSData format

How to upload image and text using HTTP POST?

or if you want more mature framework personally i advice restkit. in my project i send image to rest service with this sample code

 RKObjectManager *service = restkit_manager; //initialized previously
      [service loadObjectsAtResourcePath:@"/api/ChangeProfileImage" usingBlock:^(RKObjectLoader *loader) {
            loader.delegate      = self;
            loader.method        = RKRequestMethodPOST;
            loader.cachePolicy   = RKRequestCachePolicyNone;
            loader.objectMapping = (RKObjectMapping *) [service.mappingProvider mappingForKeyPath:MAPPING_PROFILE_IMAGE_UPDATE];

            NSMutableDictionary *params_dict = [NSMutableDictionary new];

           //custom parameters
           [params_dict setValue:UserKey forKey:@"UserKey"];

            RKParams *params = [RKParams paramsWithDictionary:params_dict];
            //encoded image
            [params setData:data MIMEType:@"image/png" forParam:@"FileName"];

            loader.params                = params;
            loader.serializationMIMEType = RKMIMETypeJSON;
        }];

this slide may give idea http://www.slideshare.net/tkalapun/restfull-with-restkit

Community
  • 1
  • 1
Ali Kıran
  • 1,006
  • 7
  • 12
0

I use ASIHTTPRequest, which is very simple and powerful. I think using this library is another choice.

My sample code is...

NSURL *url = [NSURL URLWithString:@"http://endpoint"];
NSData *data = [self addMetadata:UIImageJPEGRepresentation(self.image, 1.0)];

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[ASIFormDataRequest setDefaultTimeOutSeconds:90];
[ASIFormDataRequest setShouldThrottleBandwidthForWWAN:YES];

[request setNumberOfTimesToRetryOnTimeout:3];
[request setAllowCompressedResponse:NO];

[request setData:data withFileName:@"photo.jpg" andContentType:@"image/jpeg" forKey:@"image"];
[request startSynchronous];
JFK
  • 29
  • 1
  • 3