AFnetworking 2.2.0上传服务器上的图像问题



之所以要求您必须这样做,是因为我混淆了params。

正如我所理解的,有一种方法可以使用多部分请求来完成。

这种方式为我们提供了两个概念,正如我所理解的,从文件上传可以存储在Document目录中,也可以使用NSData对象。

从文件上传:

因此,我将test.jpg保存到了文档目录中。然后我制作了NSURL实例,以便在多部分请求中使用它。下面的代码显示了我如何创建NSURL实例:

NSString *fileName = @"test.jpg";
NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSURL *filePath = [NSURL fileURLWithPath:folderPath];

当我打印文件路径:

file:///Users/mac/Library/Application%20Support/iPhone%20Simulator/7.0.3/Applications/F732FCF6-EAEE-4E81-A88B-76ADB75EDFD1/Documents/test.jpg

然后我设置了我的参数,并使用formData将我的文件附加如下:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:@"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];

这是正确的吗?或者我错过了什么,因为回应不成功?

第二个概念-直接使用数据:

[formData appendPartWithFileData:imageData name:@"image" fileName:@"test.jpg" mimeType:@"image/jpeg"];

但当应用程序调用这行代码时,我得到了错误:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: body'

我认为在管理器块外定义的imageData在这一行为nil的原因。所以我在这里也需要帮助如何把球传给对方。

请你纠正我的步伐有什么问题,也许我错过了什么。

当我评论行时

[formData appendPartWithFileData:imageData name:@"image" fileName:@"test.jpg" mimeType:@"image/jpeg"];

[formData appendPartWithFileURL:filePath name:@"image" error:nil];

然后一切都很好,我在重新运行时得到了成功响应。

您确认在Documents文件夹中的该位置找到该文件了吗?我在协调程序确定的文件路径(这是正确的)和字符串文本文件路径(很容易出现问题)时也遇到了问题。您应该始终以编程方式确定路径,而不是使用字符串文字(因为当您重新安装应用程序时,该路径会更改)。我认为你需要的是:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"image.png"];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSError *error;
BOOL success = [formData appendPartWithFileURL:fileURL name:@"image" fileName:filePath mimeType:@"image/png" error:&error];
if (!success)
NSLog(@"appendPartWithFileURL error: %@", error);
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];

请注意,这将以编程方式确定filePath(这是一个路径,而不是URL),然后使用fileURLWithPath将其转换为文件URL。它还确认它是否成功,如果不成功,则记录错误。

还要注意,这假设您的服务器以JSON的形式返回其响应。否则,您将不得不更改responseSerializer

最新更新