14

有没有人使用 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:success:failure'(返回类型默认为'id')

在这方面的任何帮助以及使用 AFNetworks 上传都会非常棒。

谢谢。

4

1 回答 1

19

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

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

至于多部分表单块,不久前-appendWithFileData:mimeType:name也被删除了。你想要的方法是-appendPartWithFileData:name:fileName:mimeType:

进行这两项更改,一切都会正常。

于 2011-11-23T03:15:02.863 回答