简体   繁体   中英

Uploading image from gallery with AFNetworking 3.0

I checked the code example to upload images via multipart. But I don't know how get the @"file://path/to/image.jpg" value.

This is what I tried:

-(void) uploadAvatar:(NSString*)file
success:(void (^)())success failure:(void (^)())failure {


    NSString* url = [NSString stringWithFormat:@"%@%@%@", res, kApiRest, kApiServiceAvatar];
    //NSString* filepath = [NSString stringWithFormat:@"%@%@", res, kApiRest];



    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:file] name:@"file" fileName:@"image.jpg" mimeType:@"image/*" error:nil];
    } error:nil];

    //AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

    NSURLSessionUploadTask *uploadTask;
    uploadTask = [self.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];
                      });
                  }
                  completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                      if (error) {
                          NSLog(@"Error: %@", error);
                          failure();

                      } else {
                          NSLog(@"%@ %@", response, responseObject);
                          success();
                      }
                  }];

    [uploadTask resume];
}


#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [self dismissViewControllerAnimated:YES completion:nil];

    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    UIImage *imageToUse;

    // Imagen
    if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo) {
        imageToUse = (UIImage *) [info objectForKey: UIImagePickerControllerEditedImage];
        imageToUse = [imageToUse scaleToMaxWidth:kAvatarSize];


        NSData* fileHD = UIImagePNGRepresentation(imageToUse);
        APIAvatar* api = [[APIAvatar alloc] initWithUser:_user.jid password:_user.pass];
        //I have the NSData object fileHD, how can I get the path?
        [api uploadAvatar:[fileHD ] success:<#^(void)success#> failure:<#^(void)failure#>]
    } 
}

Try this solution

-(void) uploadAvatar:(NSData*)fileData
success:(void (^)())success failure:(void (^)())failure {


    NSString* url = [NSString stringWithFormat:@"%@%@%@", res, kApiRest, kApiServiceAvatar];
    //NSString* filepath = [NSString stringWithFormat:@"%@%@", res, kApiRest];



    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData: fileData
                                name:@"file"
                            fileName:@"image.jpg" mimeType:@"image/*"];
    } error:nil];

    //AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

    NSURLSessionUploadTask *uploadTask;
    uploadTask = [self.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];
                      });
                  }
                  completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                      if (error) {
                          NSLog(@"Error: %@", error);
                          failure();

                      } else {
                          NSLog(@"%@ %@", response, responseObject);
                          success();
                      }
                  }];

    [uploadTask resume];
}


#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [self dismissViewControllerAnimated:YES completion:nil];

    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    UIImage *imageToUse;

    // Imagen
    if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo) {
        imageToUse = (UIImage *) [info objectForKey: UIImagePickerControllerEditedImage];
        imageToUse = [imageToUse scaleToMaxWidth:kAvatarSize];


        NSData* fileHD = UIImagePNGRepresentation(imageToUse);
        APIAvatar* api = [[APIAvatar alloc] initWithUser:_user.jid password:_user.pass];
        //I have the NSData object fileHD, how can I get the path?
        [api uploadAvatar: fileHD success:<#^(void)success#> failure:<#^(void)failure#>]
    } 
}

Update

If you want set headers, manager's headers are ignored. Instead they should be set on request object.

[request setValue:@"myheader1" forHTTPHeaderField:@"key1"];
[request setValue:@"myheader2" forHTTPHeaderField:@"key2"];

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