我检查了代码example通过分段上传图像。
但是我不知道如何获取@“ 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#>]
    }
}

最佳答案

试试这个解决方案

-(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"];

关于ios - 使用AFNetworking 3.0从图库上传图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39516428/

10-11 00:40