简体   繁体   中英

How to upload the image/photo to a server using AFNetworking?

I am trying to upload the image/video to a webserver for iOS. The uploading part of this server works fine. I checked it with Android version and I have already implemented the uploading method in Android app. So I have found some codes for iOS on the stackoverflow.com First, I am using the following code for uploading image. But I can't upload at all and get the following result. I am using XCode6.1 on iOS8 SDK.

Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo=0x7fe24348d0b0 {NSUnderlyingError=0x7fe2434be120 "The request timed out.", NSErrorFailingURLStringKey=ServerURL, NSErrorFailingURLKey=ServerURL, NSLocalizedDescription=The request timed out.}

Here are the codes that I am using.

  NSString* serverURL = @"http://www.myserver.com/file/postMedia.php";
  UIImage *image = [UIImage imageNamed:@"sample.png"];
  NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
  NSDictionary *param = @{@"userID":@"master",


  [manager POST:serverURL parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
   [formData appendPartWithFileData:imageData name:@"uploadedfile_thumb" fileName:@"photo.jpg" mimeType:@"image/jpeg"];

} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    ....
        });

        return;
    }

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    ....
 });

Certainly, the server works fine. I have definitely tested with Android code. So I'd like to know the exact code for iOS.

Thank you

This is my working code uploading an image to the server using AFNetworking:

+ (void)uploadImage:(UIImage *)image
             ForUser:(WECUser *)user
    withSuccessBlock:(void (^)(NSDictionary *response))resultBlock
        faliureBlock:(void (^)(NSError *error))faliureBlock {
  NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

  formatter.dateFormat = @"yyyyMMddHHmmss";
  NSString *dateString = [formatter stringFromDate:[NSDate date]];
  NSString *fileName =
      [NSString stringWithFormat:@"user_image_%@.jpg", dateString];

  NSDictionary *dictionary = @{
    @"user_id" : user._id,
    @"resource_id" : user._id,
    @"functioncode" : @"2000",
    @"app_id" : [WECURLGenerator stringOfAppID],
    @"file_name" : fileName
  };

  NSURLRequest *request = [[AFHTTPRequestSerializer serializer]
      multipartFormRequestWithMethod:
          @"POST" URLString:[WECURLGenerator stringOfImageUploadingBaseURL]
                          parameters:dictionary
           constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
               [formData
                   appendPartWithFileData:UIImageJPEGRepresentation(image, 0.6)
                                     name:@"file1"
                                 fileName:fileName
                                 mimeType:@"jpg"];
           } error:(NULL)];

  AFHTTPRequestOperation *operation =
      [[AFHTTPRequestOperation alloc] initWithRequest:request];

  [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation,
                                             id responseObject) {
      NSDictionary *resultDict =
          [NSJSONSerialization JSONObjectWithData:responseObject
                                          options:NSJSONReadingMutableLeaves
                                            error:nil];
      resultBlock(resultDict[@"record"]);
  } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
      faliureBlock(error);
  }];

  [operation start];
}

Hope this helps.

Your code looks fine, I am using same code for uploading an image using AFNetworking. But you haven't mentioned how you are picking the image. Because you can not upload an image directly like:

UIImage *image = [UIImage imageNamed:@"sample.png"];

Are you using UIImagepickerController for picking your image?

If YES than see my code;

-(IBAction)chooseImg:(id)sender{

if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
    picker = [[UIImagePickerController alloc]init];
    picker.allowsEditing = NO;
    picker.delegate = self;
    picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType: UIImagePickerControllerSourceTypeCamera];
    [self.navigationController presentViewController:picker animated:YES completion:nil];
}
else{
    picker = [[UIImagePickerController alloc]init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.allowsEditing = YES;
    picker.delegate = self;
    picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    [self.navigationController presentViewController:picker animated:YES completion:nil];

}
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
NSURL *name = [info objectForKey:UIImagePickerControllerReferenceURL];
image = [info objectForKey:UIImagePickerControllerOriginalImage];
ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset *imageAsset){
    ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
    NSDictionary *metadata = imageAsset.defaultRepresentation.metadata;
    NSLog(@"Meta:%@",metadata);
    NSString *str = [imageRep filename];
    txtImg.text = str;
};
ALAssetsLibrary *assetLib = [[ALAssetsLibrary alloc]init];
[assetLib assetForURL:name resultBlock:resultBlock failureBlock:nil];
[self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

NOTE: Here I used metadata to display name of the image,it's not necessary you can skip this.

Than in uploading part:

NSString* serverURL = @"http://www.myserver.com/file/postMedia.php";
  //UIImage *image = [UIImage imageNamed:@"sample.png"];
  NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
  NSDictionary *param = @{@"userID":@"master",


  [manager POST:serverURL parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
   [formData appendPartWithFileData:imageData name:@"uploadedfile_thumb" fileName:@"photo.jpg" mimeType:@"image/jpeg"];

} success:^(AFHTTPRequestOperation *operation, id responseObject) {
....
    });

    return;
}

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
....
 });

This works for me uploading an image. Hope it works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM