我正在尝试通过REST API调用使用AFHTTPSessionManager上传图像。
以下是我的代码
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
[manager.requestSerializer setValue:@"image/jpeg" forHTTPHeaderField:@"Content-Type"];
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
[manager POST:@"http://localhost:8888/uploadImage/100" parameters:nil constructingBodyWithBlock:^(id formData) {
[formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"success:%@", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"Error:%@", error);
}];
响应将进入字段阻止并出现以下错误
错误:错误域= NSCocoaErrorDomain代码= 3840“操作无法完成。(Cocoa错误3840.)”(JSON文本没有以数组或对象开头,并且选项允许未设置片段。)UserInfo = 0x9cbc690 {NSDebugDescription = JSON文本不以数组或对象开头,并且选项允许未设置片段。,NSUnderlyingError = 0x9cbaf00“请求失败:需要长度(411)”}
有人对这个问题有所了解吗?
由于
答案 0 :(得分:0)
+(void)uploadImageData : (NSString *)url parameters:(NSDictionary *)dparameters imageData:(NSData *)dimageData success: (void (^) (NSDictionary *responseStr))success failure: (void (^) (NSError *error))failure
{
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:url]];
AFHTTPRequestOperation *op = [manager POST:url parameters:dparameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//do not put image inside parameters dictionary as I did, but append it!
[formData appendPartWithFileData:dimageData name:@"image" fileName:@"photo11.jpg" mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
//success
success(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// failure
failure(error);
}];
op.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
[op start];
}
答案 1 :(得分:0)
错误
JSON文本没有以数组或对象和允许的选项开头 片段没有设置
表示服务器默认使用iOS JSON解析器不支持的片段发送JSON。您可以在AllowFragments
上为readingOptions
设置AFJSONResponseSerializer
选项来启用它。
尝试添加(Swift)
manager.responseSerializer = AFJSONResponseSerializer(readingOptions: NSJSONReadingOptions.AllowFragments)
这解决了我。