使用AFNetworking 3.0从库中上传图像

时间:2016-09-15 16:50:06

标签: ios afnetworking-3

我检查了代码example以通过multipart上传图片。 但我不知道如何获得@“file://path/to/image.jpg”值。

这就是我的尝试:

-(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#>]
    } 
}

1 个答案:

答案 0 :(得分:2)

试试这个解决方案

-(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#>]
    } 
}

更新

如果您想要设置标头,则会忽略经理的标头。 相反,它们应该设置在请求对象上。

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