AFNetworking上传文件

时间:2011-11-22 21:40:00

标签: iphone ios afnetworking

是否有人使用AFNetworking完全上传文件。我在互联网上找到了一些代码,但它不完整。我找到的代码在这里:

AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://my.client.server.com"]];


NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
[parameters setObject:[fieldName text] forKey:@"field01_nome"];
[parameters setObject:[fieldSurname text] forKey:@"field02_cognome"];



NSMutableURLRequest *myRequest = [client multipartFormRequestWithMethod:@"POST" path:@"/Contents/mail/sendToForm.jsp" parameters:parameters constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData:myNSDataToSend mimeType:@"image/jpeg" name:@"alleagto"];
}];


AFHTTPRequestOperation *operation = [AFHTTPRequestOperation HTTPRequestOperationWithRequest:myRequest success:^(id object) {
    NSLog(@"Success");

} failure:^(NSHTTPURLResponse *response, NSError *error) {
    NSLog(@"Fail");

}];


[operation setUploadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {
    NSLog(@"Sent %d of %d bytes", totalBytesWritten, totalBytesExpectedToWrite);

}];

queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];

我在以下几行中遇到错误:

 [formData appendPartWithFileData:myNSDataToSend mimeType:@"image/jpeg" name:@"alleagto"];

在myNSDataToSend。

在这里:

AFHTTPRequestOperation *operation = [AFHTTPRequestOperation HTTPRequestOperationWithRequest:myRequest success:^(id object) {
    NSLog(@"Success");

} failure:^(NSHTTPURLResponse *response, NSError *error) {
    NSLog(@"Fail");

}];

错误是:

类方法'+ HTTPRequestOperationWithRequest:成功:失败'未找到(返回类型默认为'id')

任何有关此问题的帮助以及使用AFNetworks上传都会令人惊叹。

感谢。

1 个答案:

答案 0 :(得分:19)

首先,请确保已下载最新版本的AFNetworking。

AFHTTPRequestOperation +HTTPRequestOperationWithRequest:success:failure:已删除了几个版本。相反,您可以执行[[AFHTTPRequestOperation alloc] initWithRequest:...],然后使用直属性访问者(completionBlock)或operation.completionBlock = ^{...}设置-setCompletionBlockWithSuccess:failure:。请记住,在请求下载完成后执行完成块。

对于多部分表单块,-appendWithFileData:mimeType:name也被删除了一段时间。您想要的方法是-appendPartWithFileData:name:fileName:mimeType:

进行这两项更改,一切都应该有效。