1 //上传图片 2 -(void)upLoadImage:(UIImage *)upImage 3 { 4 //创建管理 5 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 6 //存放非文件参数 7 NSMutableDictionary *params = [NSMutableDictionary dictionary]; 8 [params setObject:@"qwe" forKey:@"userName"]; 9 //发送请求 10 [manager POST:@"http://192.168.1.27:9000/os/ks/add" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 11 12 // NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 13 // formatter.dateFormat = @"yyyyMMddHHmmss"; 14 // NSString *str = [formatter stringFromDate:[NSDate date]]; 15 // NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str]; 16 17 NSData *fileData = UIImageJPEGRepresentation(upImage, 1.0); 18 19 [formData appendPartWithFileData:fileData name:@"headFile" fileName:self.imageName mimeType:@"image/jpeg"]; 20 21 } success:^(AFHTTPRequestOperation *operation, id responSEObject) { 22 23 NSLog(@"上传成功"); 24 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 25 NSLog(@"上传失败 "); 26 }]; 27 28 }
不过需要主要的是:
不要用下面的这个方法来设置文件参数
1 [formData appendPartWithFormData:fileData name:self.imageName];
这个方法在上传图片的时候会有问题,用上面的方法就好了;
还有,在发送请求之前要判断方法内参数image是否为nil;