AFNetworking图片上传

时间:2023-01-10 06:56:39
 //上传图片
-(void)upLoadImage:(UIImage *)upImage
{
//创建管理
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//存放非文件参数
NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setObject:@"qwe" forKey:@"userName"];
//发送请求
[manager POST:@"http://192.168.1.27:9000/os/ks/add" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { // NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// formatter.dateFormat = @"yyyyMMddHHmmss";
// NSString *str = [formatter stringFromDate:[NSDate date]];
// NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str]; NSData *fileData = UIImageJPEGRepresentation(upImage, 1.0); [formData appendPartWithFileData:fileData name:@"headFile" fileName:self.imageName mimeType:@"image/jpeg"]; } success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"上传成功");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"上传失败 ");
}]; }

不过需要主要的是:

不要用下面的这个方法来设置文件参数

  [formData appendPartWithFormData:fileData name:self.imageName];

这个方法在上传图片的时候会有问题,用上面的方法就好了;

还有,在发送请求之前要判断方法内参数image是否为nil;