如何使用AFNetworking 1.3.3形成多部分表单数据请求

时间:2013-10-22 17:08:38

标签: ios afnetworking

我正在使用AFNetworking 1.3.3。

我需要向我的服务器发出multipart/form-data请求,其中包含图片数据和其他一些其他内容。

我不知道如何格式化这个多部分请求。我该怎么办?

1 个答案:

答案 0 :(得分:2)

project's GitHub page(分支1.x)上,您可以找到此示例

NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
}];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
    NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[httpClient enqueueHTTPRequestOperation:operation];

您还可以阅读documentation

相关问题