2017-04-17 124 views
1

php的iOS上传图片PHP返回空

Upload方法:

/** 
    * ### this function is file upload 
    * auto file name and file path 
    * @param $FILES File to file 
    * @param string $A 
    * @param string $B 
    * @return bool|string 
    */ 
    protected function Upload($FILES,$A="",$B=""){ 
     $ReturnFILE = array(); 
     $FILES = array_keys($FILES); 
     foreach ($FILES as $K => $V) { 
      $FlodName = "Updata/".date("Y-m-d"); 
      if(!is_dir($FlodName)){ 
       mkdir($FlodName,777,true); 
      } 
      if ($_FILES[$FILES[$K]]["error"] > 0){ 
       return false; 
      } 
      $tempEXT = strstr($_FILES[$FILES[$K]]["name"],"."); 
      $FileName = date("YmdHis").UUID().$tempEXT; 
      move_uploaded_file($_FILES[$FILES[$K]]["tmp_name"],"{$FlodName}/" . $FileName); 
      $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://'; 
      $FileName =$http_type.$_SERVER['HTTP_HOST']."/".$FlodName."/".$FileName; 
      $ReturnFILE[] = $FileName; 
     } 
     return $ReturnFILE; 
    } 

ImageEdit方法使用Upload方法上载iOS应用程式绕过图片:

public function ImgEdit() 
{ 

    $imgs=$this->Upload($_FILES); 
    var_dump($imgs); 
    // success 
    if (!empty($imgs)){ 
     echo 1; 
     $datas = [ 
      'code' => 200, 
      'message' => "修改成功", 
      'data' =>$imgs 
     ]; 
     echo json_encode($datas); 
    } else { // fail 
     echo 2; 
     $datas = [ 
      'code' => 0, 
      'message' => "修改失败", 
      'data' => "" 
     ]; 
     echo json_encode($datas); 
    } 
} 

在iOS应用程序,我用这种方法上传我的图片:

- (void)networkUploadHeadImage:(UIImage *)image { 

    UIImage *img = image; 
    NSData *dataObj = UIImagePNGRepresentation(img); 

    NSDictionary * param1 = @{ 
           @"imgFile":dataObj 
           }; 
    AFHTTPSessionManager * session = [AFHTTPSessionManager manager]; 
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"application/xml",@"text/json",@"text/javascript",@"text/html",@"text/plain",@"multipart/form-data",nil]; 

    //拼接地址 
    NSString *url = @"http://103.71.178.145:8088/Home/Aboutus/ImgEdit"; 

    [session POST:url parameters:param1 constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { 

     UIImage *img = image; // response 
     NSData *data = UIImagePNGRepresentation(img); 

     [formData appendPartWithFileData:data name:@"imgFile" fileName:@"imgFile.png"mimeType:@"image/png"]; 
    } success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) { 

     NSLog(@"success+%@", responseObject); 

     //保存 
     NSString *result_url_str = responseObject[@"data"]; 

    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) { 
     NSLog(@"fail"); 

    }]; 
} 

结果是:

,如果我用iOS的方法来上传自己的形象:

的数据库中,我们可以看到上传的图片,它的成功,但在ImageEdit法,$imgs是空的:

var_dump($imgs); the `$imgs` is empty. 

我的iOS应用程序执行:NSLog(@"fail");

如果我使用HTML表单提交:

<html> 
<body> 

<form action="Insert" method="post" 
     enctype="multipart/form-data"> 
    <label for="file">Filename:</label> 
    <input type="file" name="file" id="file" /> 
    <br /> 
    <input type="submit" name="submit" value="Submit" /> 
</form> 

</body> 
</html> 

我会得到$imgs,它有上传的图片的路径。

为什么我用- (void)networkUploadHeadImage:(UIImage *)image得不到任何关于$imgs


编辑

如果我使用KK的回答是:

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@%@",BASEURL,url] parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 
      if (image) { 
       [formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.8) name:@"imagename" fileName:@"Image.jpg" mimeType:@"image/jpeg"]; 
      } 

     }error:nil]; 

     AFURLSessionManager * urlSessionmanager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 

     urlSessionmanager.responseSerializer = [AFJSONResponseSerializer serializer]; 
     NSURLSessionUploadTask *uploadTask; 
     uploadTask = [urlSessionmanager 
         uploadTaskWithStreamedRequest:request 
         progress:^(NSProgress * _Nonnull uploadProgress) { 

         } 
         completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { 
          if (error) { 

           NSLog(@"error:%@", error); 
          } else { 
          // successfully uploaded 
          } 
         }]; 

     [uploadTask resume]; 

我会打印错误信息:

错误域= com.alamofire.error.serialization .response Code = -1016“Request failed:unacceptable content-type:text/html”UserInfo = {com.alamofire.se rialization.response.error.response = {URL:http://103.71.178.145:8088/Home/Aboutus/ImgEdit} {status code:200,headers'Cache-Control“=”no-store,no-cache,must-revalidate,post-check = 0,pre-check = 0" ; “Content-Length”= 239; “Content-Type”=“text/html; charset = utf8”; 日期=“星期一,2017年4月17日11:18:20 GMT”; Expires =“星期四,1981年11月19日08:52:00 GMT”; Pragma =“no-cache”; Server =“Microsoft-IIS/7.5”; “Set-Cookie”=“PHPSESSID = a5n20to0r0ahk554ppa79jfp56; path = /”; “X-Powered-By”=“PHP/5.4.33,ASP.NET”; }},NSErrorFailingURLKey = http://103.71.178.145:8088/Home/Aboutus/ImgEdit,com.alamofire.serialization.response.error。数据= < 0d0a3231 6e676e67 32617272 61792831 29207b0a 20205b30 5d3d3e0a 20207374 72696e67 28363329 20226874 74703a2f 2f313033 2e37312e 3137382e 3134353a 38303838 2f557064 6174612f 32303137 2d30342d 31372f32 30313730 34313731 39313832 302e6a70 67220a7d 0a317b22 636f6465 223a3230 302c226d 65737361 6765223a 225c7534 6665655c 75363533 395c7536 3231305c 75353239 66222c22 64617461 223a5b22 68747470 3a5c2f5c 2f313033 2e37312e 3137382e 3134353a 38303838 5c2f5570 64617461 5c2f3230 31372d30 342d3137 5c2f3230 31373034 31373139 31383230 2e6a7067 225d7d>,NSLocalizedDescription =请求失败:无法接受的内容类型:text/html的}

但是,如果我上传喜欢KK的更新的方法是这样的:

UIImage *img = image; 
NSData *dataObj = UIImagePNGRepresentation(img); 

NSString *url = @"http://103.71.178.145:8088/Home/Aboutus/ImgEdit"; 

NSDictionary * param1 = @{ 
          @"imgFile":dataObj 
          }; 


NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:param1 constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 
    if (image) { 
     [formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.8) name:@"imagename" fileName:@"Image.jpg" mimeType:@"image/jpeg"]; 
    } 

}error:nil]; 

AFURLSessionManager * urlSessionmanager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 

urlSessionmanager.responseSerializer = [AFHTTPResponseSerializer serializer]; 

NSURLSessionUploadTask *uploadTask; 
uploadTask = [urlSessionmanager 
       uploadTaskWithStreamedRequest:request 
       progress:^(NSProgress * _Nonnull uploadProgress) { 

       } 
       completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { 
        if (error) { 

         NSLog(@"err=%@", error); 
        } else { 
         // successfully uploaded 
         NSLog(@"success= %@, === %@", response, responseObject); 
        } 
       }]; 

[uploadTask resume]; 

尽管我成功了,但没有得到返回的URL,PHP并没有将URL(图像的路径)返回给我。

见我的日志:

2017年4月17日19:34:50.058 uploadImgTool [73016:16061592]成功= {URL:http://103.71.178.145:8088/Home/Aboutus/ImgEdit} {状态码:200,标头{ “缓存控制“=”no-store,no-cache,must-revalidate,post-check = 0,pre-check = 0“; “Content-Length”= 232; “Content-Type”=“text/html; charset = utf8”; 日期=“星期一,2017年4月17日11:34:24 GMT”; Expires =“星期四,1981年11月19日08:52:00 GMT”; Pragma =“no-cache”; Server =“Microsoft-IIS/7.5”; “Set-Cookie”=“PHPSESSID = 1qqv4nnp5gf5o8nqcuhve12ds2; path = /”; “X-Powered-By”=“PHP/5.4.33,ASP.NET”; }},=== < 0d0a6172 72617928 3129207b 0a20205b 305d3d3e 0a202073 7472696e 67283633 29202268 7474703a 2f2f3130 332e3731 2e313738 2e313435 3a383038 382f5570 64617461 2f323031 372d3034 2d31372f 32303137 30343137 31393334 32342e6a 7067220a 7d0a317b 22636f64 65223a32 30302c22 6d657373 61676522 3a225c75 34666565 5c753635 33395c75 36323130 5c753532 3966222c 22646174 61223a5b 22687474 703a5c2f 5c2f3130 332e3731 2e313738 2e313435 3a383038 385c2f55 70646174 615c2f32 3031372d 30342d31 375c2f32 30313730 34313731 39333432 342e6a70 67225d7d使用我下面的代码片段>

回答

1

尝试上传图片。

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@%@",BASEURL,url] parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 
      if (image) { 
       [formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.8) name:@"imagename" fileName:@"Image.jpg" mimeType:@"image/jpeg"]; 
      } 

     }error:nil]; 

     AFURLSessionManager * urlSessionmanager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 

    urlSessionmanager.responseSerializer = [AFHTTPResponseSerializer serializer]; 

     NSURLSessionUploadTask *uploadTask; 
     uploadTask = [urlSessionmanager 
         uploadTaskWithStreamedRequest:request 
         progress:^(NSProgress * _Nonnull uploadProgress) { 

         } 
         completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { 
          if (error) { 


          } else { 
          // successfully uploaded 
          } 
         }]; 

     [uploadTask resume]; 
+0

我测试你的方法,但我得到的错误。 –

+0

看到我的编辑,兄弟。 –

+0

你得到了哪个错误。在这里添加 – KKRocks