2014-01-22 64 views
0

我只想上傳一個.dat文件從一個Windows手機到一個PHP腳本。如何使用windows phone base64編碼文件並上傳到PHP?

這是我的代碼,但不起作用。任何人都可以看到爲什麼?

C#:

string fileBase64 = "UklGRt4lAABXQVZFZm10IBAAAAABAAEARKw..."; 

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://...mysite.../upload.php"); 
request.Method = "POST"; 
request.ContentType = "application/octet-stream"; 

string postData = String.Format("file={0}", fileBase64); 

// Getting the request stream. 
request.BeginGetRequestStream 
    (result => 
    { 
     // Sending the request. 
     using (var requestStream = request.EndGetRequestStream(result)) 
     { 
      using (StreamWriter writer = new StreamWriter(requestStream)) 
      { 
       writer.Write(postData); 
       writer.Flush(); 
      } 
     } 

     // Getting the response. 
     request.BeginGetResponse(responseResult => 
     { 
      var webResponse = request.EndGetResponse(responseResult); 
      using (var responseStream = webResponse.GetResponseStream()) 
      { 
       using (var streamReader = new StreamReader(responseStream)) 
       { 
        string srresult = streamReader.ReadToEnd(); 
       } 
      } 
     }, null); 
    }, null); 

PHP:

define("UPLOAD_DIR", "./uploads/"); 


    if(isset($_POST['file'])) 
    { 
     $base64_string = $_POST['file']; 
     $ifp = fopen(UPLOAD_DIR.'aaa.dat', "wb"); 
     fwrite($ifp, base64_decode($base64_string)); 
     fclose($ifp); 

     echo "ok"; 
     echo $base64_string; 
     echo base64_decode($base64_string); 

    }else{ 
      echo "no submit"; 
     } 
+2

你是什麼意思的「不工作」?怎麼了? – drankin2112

+0

要回應上述評論,請描述您所看到的行爲以及收到的任何異常情況。另外,如果你只是將文件保存到最後,爲什麼要直接發佈基本64字符串而不是文件內容? – lsuarez

回答

0

你濫用HTTP協議。

這是the correct way to upload files到服務器。一定要閱讀評論,你也可能想要異步做到這一點。對於異步路徑,我建議您嘗試C#語言的新異步等待功能,與開始/結束方法相比,這對於此類任務非常有用。

相關問題