我正在使用AFNetworking和AFJSONRequestOperation使用此代码将图像连同一些参数发布到我的 REST 服务器。
NSData* uploadFile = nil;
if ([params objectForKey:@"file"]) {
uploadFile = (NSData*)[params objectForKey:@"file"];
[params removeObjectForKey:@"file"];
}
NSMutableURLRequest *apiRequest =
[self multipartFormRequestWithMethod:@"POST"
path:kAPIPath
parameters:params
constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
if (uploadFile) {
[formData appendPartWithFileData:uploadFile
name:@"file"
fileName:@"photo.jpg"
mimeType:@"image/jpeg"];
[formData throttleBandwidthWithPacketSize:5000 delay:kAFUploadStream3GSuggestedDelay];
}
}];
AFHTTPRequestOperation *operation2 = [[AFJSONRequestOperation alloc] initWithRequest: apiRequest];
[operation2 setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation2, id responseObject) {
//success!
completionBlock(responseObject);
} failure:^(AFHTTPRequestOperation *operation2, NSError *error) {
//failure :(
completionBlock([NSDictionary dictionaryWithObject:[error localizedDescription] forKey:@"error"]);
}];
[operation2 setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
if (self.delegate) {
NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
[self.delegate didReceiveData:(totalBytesWritten / (float)totalBytesExpectedToWrite)];
}
}];
[[API sharedInstance] enqueueHTTPRequestOperation:operation2];
这随机工作。我的意思是有时一切都完美无缺,有时进度卡在发送过程的中间并以超时错误结束。
我尝试了很多参数和不同的组合,但我的行为总是相同的。
PS:我使用框架的最新版本。
PS2:我所有的测试都是在模拟器和设备上进行的,也通过 Wifi 连接进行