iOS - 由Resty将图像发布到服务器

时间:2012-08-20 07:35:50

标签: iphone ios rest http-headers

之前我使用this method将图像发布到服务器,但它有点复杂,因为我必须自己添加标题和边界。昨天我发现了一个名为Resty的项目 - “iOS和Mac的简单Objective-C HTTP客户端”。但是,在阅读完所有文档后,我找不到任何上传图像文件的方法。请帮助,非常感谢。

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");
}];

2 个答案:

答案 0 :(得分:0)

我认为此框架无法正确处理图像数据和自定义参数您可以遵循此主题并创建正确的NSData格式

How to upload image and text using HTTP POST?

或者如果您想要更成熟的框架,我建议restkit。 在我的项目中,我使用此示例代码将图像发送到休息服务

 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;
        }];

此幻灯片可能会提供http://www.slideshare.net/tkalapun/restfull-with-restkit

的提示

答案 1 :(得分:0)

我使用ASIHTTPRequest,这非常简单而且功能强大。 我认为使用这个库是另一种选择。

我的示例代码是......

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];