2016-09-23 148 views
1

请问我一直在试图从xamarin表单应用程序上传图片到php服务器,但似乎没有工作。服务器收到一个空的$ _FILES请求。这是C#代码。将图片从xamarin表单上传到php服务器

public async Task<bool> Upload(MediaFile mediaFile, string filename) 
    { 
     byte[] bitmapData; 
     var stream = new MemoryStream(); 
     mediaFile.GetStream().CopyTo(stream); 
     bitmapData = stream.ToArray(); 
     var fileContent = new ByteArrayContent(bitmapData); 

     fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream"); 
     fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") 
     { 
      Name = "fileUpload", 
      FileName = filename 
     }; 

     string boundary = "---8393774hhy37373773"; 
     MultipartFormDataContent multipartContent = new MultipartFormDataContent(boundary); 
     multipartContent.Add(fileContent); 


     HttpClient httpClient = new HttpClient(); 
     HttpResponseMessage response = await httpClient.PostAsync("http://www.url.com/upload.php", multipartContent); 
     response.EnsureSuccessStatusCode(); 

     if (response.IsSuccessStatusCode) 
     { 
      string content = await response.Content.ReadAsStringAsync(); 

      return true; 
     } 
     return false; 
    } 

下面是接收上传图片的php文件。我试图将发布图像的内容保存到文件中,但该文件只有一个空数组,并且始终返回“失败”。请问我错过了什么?我搜查了网页,但似乎无法理解这个问题。

$uploads_dir = 'uploads/'; 
    $req_dump = print_r($_FILES, true); 
    $fp = file_put_contents('data.txt', $req_dump); 
    if (isset($_FILES["fileUpload"]["tmp_name"]) AND is_uploaded_file($_FILES["fileUpload"]["tmp_name"])) 
    { 
    $tmp_name = $_FILES["fileUpload"]["tmp_name"]; 
    $name = $_FILES["fileUpload"]["name"]; 
    $Result = move_uploaded_file($tmp_name, "$uploads_dir/$name"); 
    echo "Success"; 
    } 
    else 
    { 
    echo "Failure"; 
    } 
+0

在C#代码我改变' “应用/八位字节流”''到 “图像/ JPG”'。然后在PHP只是'move_uploaded_file($ _ FILES [“image”] [“tmp_name”],'路径');'工作正常。从简单的事情开始,然后添加条件来看看会发生什么 – dev

回答

0

AND运算符对你来说真的不是一个好选择。 (在线4)。有时会显示一些非常意想不到的行为。 (我可以参考'AND' vs '&&' as operator了解更多信息)。

如果您想要逻辑AND,请使用运算符& &。 线将是

if (isset($_FILES["fileUpload"]["tmp_name"]) && is_uploaded_file($_FILES["fileUpload"]["tmp_name"])) 
+0

我将AND更改为&&但仍然存在相同的问题。 –