AFNetworking HTTP POST上传图像在接近完成时停止

时间:2013-04-17 10:08:26

标签: iphone ios cocoa-touch http-post afnetworking

我正在使用以下代码来HTTP POST多部分网页表单,包括JPEG图像。

代码:

NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
[params setObject:nameField.text forKey:@"name"];
[params setObject:emailField.text forKey:@"email"];
[params setObject:titleField.text forKey:@"title"];
[params setObject:dateString forKey:@"link"];
[params setObject:descriptionTV.text forKey:@"content"];
[params setObject:tag forKey:@"tags"];

NSData* sendData = UIImageJPEGRepresentation(uploadedPhoto.image, 1.0);
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://example.com/"]];
NSMutableURLRequest *afRequest = [httpClient multipartFormRequestWithMethod:@"POST"
                                                                       path:@"form"
                                                                 parameters:params
                                                  constructingBodyWithBlock:^(id <AFMultipartFormData>formData)
                                  {
                                      [formData appendPartWithFileData:sendData
                                                                  name:@"image"
                                                              fileName:@"image.jpeg"
                                                              mimeType:@"image/jpeg"];
                                  }];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:afRequest];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {

    NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"SUCCESS! %@", operation.responseString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"FAILED!!! %@", operation.responseString);
}];

[operation start];

网络表单

<input type="text" name="name" id="name" value="" />
<input type="text" name="email" id="email" value="" />
<input type="text" name="title" id="title" value="" />
<input type="text" name="link" id="link" value="" />
<input type="text" name="content" id="content" value="" />
<input type="text" name="tags" id="tags" value="" />
<input type="file" name="image" id="image" value="" />

每次运行代码时,图像上传都会顺利进行,直到上传进度即将完成(~99.5%已完成)。操作的completionBlockWithSuccess:failure:块永远不会启动,应用程序就会冻结。

任何人都可以帮我解决这个问题吗?我不知道我在这里做错了什么。

修改

我做了一些调查,发现即使使用无效的请求路径它也是如此,但我很确定我没有错误地键入我的表单路径。此外,当我将constructingBodyWithBlock块替换为nil时,它将正常工作。

编辑2:

我在AFNetworking的Github上做了一些窥探,找到了a Github issue posta similar post on Stack Overflow。我尝试使用[httpClient enqueueHTTPRequestOperation:operation];代替[operation start];并使httpClient成为单身,但同样的问题仍然存在。

1 个答案:

答案 0 :(得分:0)

您是否尝试在失败回调中打印NSError?也许服务器期待另一种mime类型。