我正在使用 Afnetworking 3.0,对于带有其他一些参数的图像上传,我使用此代码
NSData *imageToUpload = UIImageJPEGRepresentation(_profileImageView.image, 1.0);//(uploadedImgView.image);
NSMutableDictionary * params = [[NSMutableDictionary alloc] init];
[params setValue:_tf_email.text forKey:@"email"];
[params setValue:_tf_password.text forKey:@"password"];
[params setValue:_tf_userType.text forKey:@"userType"];
[params setValue:_tf_country.text forKey:@"country"];
[params setValue:_tf_name.text forKey:@"name"];
[params setValue:@"3.423434" forKey:@"longitude"];
[params setValue:@"72.32445" forKey:@"latitude"];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@%@",BaseUrl,Register] parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageToUpload name:@"profilePicture" fileName:[NSString stringWithFormat:@"%@.jpeg",_tf_name.text] mimeType:@"image/jpeg"];
} error:nil];
// AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"charset=UTF-8", nil];
manager.responseSerializer = responseSerializer;
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
//[progressView setProgress:uploadProgress.fractionCompleted];
NSLog(@"%f",uploadProgress.fractionCompleted);
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
}
}];
[uploadTask resume];
注意:profilePicture 是我为它提供服务的关键错误错误:错误域 = NSCocoaErrorDomain 代码 = 3840“字符 1 周围的值无效。” UserInfo={NSDebugDescription=字符 1 周围的值无效。}