AFNetworking上传文件

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

在我的NSDataToSend中。

还有这里:

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

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

}];

错误内容为:

类方法“+HTTPRequestOperationWithRequest:success:failure”未找到(返回类型默认为“id”)

对此问题的任何帮助,以及使用AFNetworks上传的经验都将是惊人的。

谢谢。

1个回答

19

首先,确保你已经下载了最新版本的AFNetworking。

AFHTTPRequestOperation +HTTPRequestOperationWithRequest:success:failure: 这个方法已经几个版本前被移除了。现在你可以用 [[AFHTTPRequestOperation alloc] initWithRequest:...] 来替代,并且使用直接属性访问器(operation.completionBlock = ^{...})或者 -setCompletionBlockWithSuccess:failure: 来设置 completionBlock。需要注意的是,完成块会在请求结束后执行。

至于multipart表单块,-appendWithFileData:mimeType:name也被删除了一段时间。现在你需要用 -appendPartWithFileData:name:fileName:mimeType: 方法。

进行这两个更改后,应该就能正常工作了。


哦,我仍然在(a)查找AFHTTPClient.m中的方法并且(b)遇到编译错误。除了我的错误显示“匿名类的声明必须是定义”,我该去哪里修复它? - buildsucceeded
1
@mattt,我可以在使用multipartFormRequestWithMethod方法上传图片时将内容类型从multipart/form-data;更改为image/jpeg吗?需要您的帮助! - Almas Adilbek
@AlmasAdilbek 不是。你正在发送一个带有JPEG部分的多部分表单,而不是仅仅是JPEG。 - mattt
@mattt 面临同样的问题,正在寻找一些函数让我可以上传一个文件。 - jeswang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接