我使用AFNetworking最新版本并尝试使用不同的方式上传图片:
NSString *urlString = [baseUrlString stringByAppendingString:@"account/avatar"];
NSDictionary *parameters = @{@"token": self.token};
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
} error:nil];
[request setValue:self.token forHTTPHeaderField:@"token"];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
// uploadTask = [manager
// uploadTaskWithStreamedRequest:request
// progress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
// if (error) {
// NSLog(@"Error: %@", error);
// } else {
// NSLog(@"%@ %@", response, responseObject);
// }
// }];
//
uploadTask = [manager uploadTaskWithRequest:request fromData:[NSData dataWithContentsOfURL:filePath] progress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
}
}];
[uploadTask resume];
在node.js中,网页上传文件运行良好,但如果使用AFNetworking:
console.log(req.files);//print TypeError: Cannot read property of undefined