找到你要的答案

Q:Image upload from photo library in ios using AFNetworking?

Q:从iOS使用AFNetworking图片库上传图像?

I am developing an app in which a user need to register. There is an image upload option where the user can pick an image from the photo library in iPhone. I have used AFNetworking for uploading. But there is error in multipart uploading, Error log attached with this question. If anyone know the solution please help me

Thanks in advance.

iOS PART

- (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 PART

<?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";
    }
    ?>

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.}

我正在开发一个用户需要注册的应用程序。有一个图像上传选项,用户可以选择一个图像从照片库在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数据= uiimagejpegrepresentation(图像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.}
answer1: 回答1:

I quick looked your code and found

NSData *data = UIImageJPEGRepresentation(image, 0.5);

And you specified mimeType as "image/png", I think this may cause error.

我快速查看你的代码并找到

NSData数据= uiimagejpegrepresentation(图像0.5);

你指定的文件类型为“图像/格式”,我认为这可能会导致错误。

answer2: 回答2:

Try this:

-(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);
 }];}

试试这个:

-(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);
 }];}
php  ios  objective-c  iphone  afnetworking