0

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

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

2 回答 2

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];
于 2012-08-24T05:52:29.480 回答
0

我认为这个框架不能正确处理图像数据和自定义参数你可以关注这个主题并创建正确的 NSData 格式

如何使用 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

于 2012-08-23T07:38:42.403 回答