使用 AFNetworking 从 ios 中的照片库上传图像?

Posted

技术标签:

【中文标题】使用 AFNetworking 从 ios 中的照片库上传图像?【英文标题】:Image upload from photo library in ios using AFNetworking? 【发布时间】:2015-10-08 10:06:04 【问题描述】:

我正在开发一个用户需要注册的应用。有一个图像上传选项,用户可以从 iPhone 的照片库中选择图像。我使用 AFNetworking 进行上传。但是分段上传有错误,这个问题附有错误日志。如果有人知道解决方案,请帮助我

提前致谢。

iOS 部分

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage * image = info [UIImagePickerControllerOriginalImage];

    NSString *fileName = [NSString stringWithFormat:@"%ld%c%c.jpg", (long)[[NSDate date] timeIntervalSince1970], arc4random_uniform(26) + 'a', arc4random_uniform(26) + 'a'];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSData *data = UIImageJPEGRepresentation(image, 0.5);
   // NSLog(@"DATA %@",data);
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *key1 = @"123";
    NSString *key2 = @"asdf";


     [manager POST:@"http://192.168.0.100/fileupload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) 
        [formData appendPartWithFileData:data
                                    name:@"uploadedfile"
                                fileName:fileName mimeType:@"image/png"];

        [formData appendPartWithFormData:[key1 dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"email"];

        [formData appendPartWithFormData:[key2 dataUsingEncoding:NSUTF8StringEncoding]
                                    name:@"website"];

        // etc.
     success:^(AFHTTPRequestOperation *operation, id responseObject) 
        NSError *error = nil;
        NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
        if (error) 
            NSLog(@"Error serializing %@", error);
        
        NSLog(@"Dictionary %@", JSON);     failure:^(AFHTTPRequestOperation *operation, NSError *error) 
        NSLog(@"Error: %@", error);
    ];

php部分

<?php
    $uploaddir = 'uploads/';
    $file = basename($_FILES['uploadedfile']['name']);
    $uploadfile = $uploaddir . $file;

    echo "file=".$file; //is empty, but shouldn't

    if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $uploadfile)) 
        echo $file;
    
    else 
        echo "error";
    
    ?>

错误

  imageupload[23252:237255] Error serializing Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Something looked like a 'false' but wasn't around character 0.) UserInfo=0x7fee21fe1590 NSDebugDescription=Something looked like a 'false' but wasn't around character 0.

【问题讨论】:

【参考方案1】:

我快速查看了您的代码并找到了

NSData *data = UIImageJPEGRepresentation(image, 0.5);

而你将 mimeType 指定为“image/png”,我认为这可能会导致错误。

【讨论】:

那么 mimeType 应该是什么? AFHTTPRequestOperationManager 的 responseSerializer 默认为 AFJSONResponseSerializer,您的 php 脚本似乎没有返回 json 响应。【参考方案2】:

试试这个:

-(void) uploadImage 

NSString *imagePath = [[NSUserDefaults standardUserDefaults] objectForKey:@"userimage"];
NSString * urlString = [stagingURL stringByReplacingOccurrencesOfString:@"user/" withString:@""];
NSString * uploadURL = @"Your URL where image to be uploaded";
NSLog(@"uploadImageURL: %@", uploadURL);
NSData *imageData = UIImageJPEGRepresentation([UIImage imageWithData:[NSData dataWithContentsOfFile:imagePath]], 0.5);

NSString *queryStringss = [NSString stringWithFormat:@"%@",uploadURL];
queryStringss = [queryStringss stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer=[AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

[manager POST:queryStringss parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) 
     [formData appendPartWithFileData:imageData name:@"file" fileName:@"file" mimeType:@"image/jpeg"];
 
      success:^(AFHTTPRequestOperation *operation, id responseObject) 

     NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);
     [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
 
      failure:^(AFHTTPRequestOperation *operation, NSError *error) 
     [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
     NSLog(@"Error: %@ ***** %@", operation.responseString, error);
 ];

【讨论】:

如何从图像选择器控制器获取图像路径?

以上是关于使用 AFNetworking 从 ios 中的照片库上传图像?的主要内容,如果未能解决你的问题,请参考以下文章

在 iOS8 上使用 UIImagePicker 结果 URL 和 PHAsset 从“我的照片流”加载图像

在 iOS 5 中使用 AFNetworking 解析 JSON

iOS - 使用 AFNetworking 保存和持久化 JSON 结果的策略

使用 AFNetworking 将 Firebase 通知从 ios 设备推送到花药

PHP REST 服务中的 JSON 格式问题从 AFNetworking 2.0 接收 POST

如何在 iOS 中使用 AFNetworking 从 REST 接口定期轮询/拉取