在单个 PHP 中使用 AFNetworking 2.0 上传图像和信息(两者)

Posted

技术标签:

【中文标题】在单个 PHP 中使用 AFNetworking 2.0 上传图像和信息(两者)【英文标题】:Upload Image and Information (both) Using AFNetworking 2.0 in Single PHP 【发布时间】:2014-06-21 15:46:35 【问题描述】:

我正在尝试使用 AFNetworking 2.0 上传多张图片(产品图片)和信息(品牌名称、价格等)。

我确实设法使用两个单独的 php 文件上传图像和信息 1.upload_product_info.php 2.upload_product_images.php,

在成功调用upload_product_images.php 时首先调用upload_product_info.php。一切正常,但我希望它使用单个 php 文件。

我尝试了单个 PHP,但它部分工作并且没有给出任何错误只上传图像,数据库中的产品信息字段(产品品牌,名称等)总是空白。我不明白我做错了什么。我是php新手。

这是我上传图片和信息的 ios 代码。

- (IBAction)uploadProduct:(id)sender 

// for Testing purpose just taken 2 fields.
  NSString *productbrand  = @"xyz";
  NSString *productname   = @"pqr";

  NSDictionary *infoDictionary = @@"pbrand": productbrand, @"pname": productname;

  __block NSUInteger success = 0;
  __block NSString *message;
  static int count = 1;

// returns array of product images url from temp Directory.
  productImages = [self returnImagesFromTemporaryDirectory];

  AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

  manager.requestSerializer = [AFJSONRequestSerializer serializerWithWritingOptions:NSJSONWritingPrettyPrinted];
  manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];

  [manager POST:@"http://localhost/~abc/Website/uploadProduct.php" parameters:infoDictionary constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
  
    for (NSURL *filePath in productImages)
    

      CFStringRef pathExtension = (__bridge_retained CFStringRef)[filePath pathExtension];
      CFStringRef type = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, NULL);
      CFRelease(pathExtension);

      NSString *mimeType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass(type, kUTTagClassMIMEType);
      NSLog(@" Mime Type : %@", mimeType);

      NSString *imageName = [NSString stringWithFormat:@"IMG00%i.png",count];
      count++;

      [formData appendPartWithFileURL:filePath name:@"uploaded_file[]" fileName:imageName mimeType:mimeType error:nil];
    
  
    success:^(AFHTTPRequestOperation *operation, id responseObject)
   
     NSDictionary *responseDic = (NSDictionary *)responseObject;

     success = [responseDic[@"success"] integerValue];
     NSLog(@"Success: %ld",(long)success);
     message = responseDic[@"message"];

     if (success == 1)
     
       UIAlertView *successAlert = [[UIAlertView alloc] initWithTitle:@" Success " message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];

       [successAlert show];
     

   
    failure:^(AFHTTPRequestOperation *operation, NSError *error)
   
     NSLog(@"Error: %@ ***** %@", operation.responseString, error);

     UIAlertView *failedAlert = [[UIAlertView alloc] initWithTitle:@" Failed " message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];

     [failedAlert show];
  ];

这是我的用于图像+信息上传的 PHP。

   <?php

    header('Content-type: application/json');

    $json = file_get_contents('php://input'); // Catching input
    $value= json_decode($json, true);   // Decode JSON into Dictionary.

    $response = array();

// retrieve values from Dictionary using key.
    $productBrand = $value['pbrand'];
    $productname  = $value['pname'];


    // Database Connection.
    $mysqlserver="localhost";
    $mysqlusername="abc123";
    $mysqlpassword="pqr123";
    $link=mysql_connect($mysqlserver, $mysqlusername, $mysqlpassword) or die ("Error connecting to mysql server: ".mysql_error());

    $dbname = 'myDatabase';    // change this to the name of your database
    mysql_select_db($dbname, $link) or die ("Error selecting specified database on mysql server: ".mysql_error()); 

    // Insert Data into Table.
     $insertQuery = "INSERT INTO user_test (productBrand, productName) VALUES ('$productBrand', '$productname')";

    $result = mysql_query($insertQuery);

    if($result) 
    
        $count=0;

             foreach ($_FILES['uploaded_file']['name'] as $filename) 
            
                $file_path="uploads/";             

                $tmp=$_FILES['uploaded_file']['tmp_name'][$count];

                move_uploaded_file($tmp,$file_path.$filename);         

             $count=$count + 1;
            

            $response["success"] = 1;
            $response["message"] = "Images uploaded Successfully.";
     
    else
    
            $response["success"] = 0;
            $response["message"] = "Failed to upload Images";
    

    echo json_encode($response);

     ?>

【问题讨论】:

【参考方案1】:

问题似乎出在 PHP 方面 线条

$json = file_get_contents('php://input'); // Catching input
$value= json_decode($json, true);   // Decode JSON into Dictionary.

不工作。用这一行替换上面的块

$value= $_REQUEST;

应该可以解决您的问题。

【讨论】:

谢谢你wooknight。它解决了我的问题,非常感谢您的帮助。

以上是关于在单个 PHP 中使用 AFNetworking 2.0 上传图像和信息(两者)的主要内容,如果未能解决你的问题,请参考以下文章

如何在 iOS 中使用 AFNetworking 将数据发送到 php 服务器

使用 AFNetworking 和 PHP 从照片库上传选定的图像

AFNetworking 使用 NSMutableURLRequest 上传?

在 AFNetworking 中支持 SNI

AFNetworking 将 NSDictionary 作为单个数组值发送,而不是作为完整对象发送

iOS - 连接 PHP 页面时 AFNetworking 失败