2012-10-31 71 views
0

我上傳的PHP服務器上的C#代碼的文件。但是面臨一些問題。C#文件使用PHP服務器上的字符串上傳

首先我使用的是WebClient的對象通過調用UploadFile()方法來上傳文件,並通過調用UploadString()方法,通過下面的代碼上傳字符串:

 String StoreID = "First Store"; 
     WebClient Client = new WebClient(); 
     String s = Client.UploadString("http://localhost/upload.php", "POST", StoreID); 
     Client.Headers.Add("Content-Type","binary/octet-stream"); 
     byte[] result = Client.UploadFile("http://localhost/upload.php", "POST", "C:\\aaaa.jpg"); 
     s = s + System.Text.Encoding.UTF8.GetString(result,0,result.Length); 

的問題是,我請求兩次所以字符串和文件不會被同時發送。我正在接收字符串或文件。但我同時需要兩者。我不想使用UploadData()因爲它會使用字節碼,我知道我的想法如何在PHP中提取它。

讓字符串是文件夾名稱,我必須發送字符串和文件,以便該文件可以保存在指定的文件夾在PHP服務器。

我研究過的可能有WebRequest和WebResponse對象的解決方案。但不知道如何通過C#使用WebResponse發送請求並在PHP中獲取它。

任何建議!

+0

參見:http://stackoverflow.com/questions/2950292/how-to-upload-multiple-files-using-webclient-uploadfile-uploadvalues-in-c –

回答

0

試試這個:

WebClient web = new WebClient(); 
try{ 

    web.UploadFile("http://" + ip + "/test.php", StoreID); 
} 
catch(Exception e) 
{ 
    MessageBox.Show("Upload failed"); 
} 

現在你可以從PHP文件訪問文件。

<?php 
//check whether the folder the exists 
if(!(file_exists('C:/Users/dhanu-sdu/Desktop/test'))) 
{ 
    //create the folder 
    mkdir('C:/Users/ComputerName/Desktop/test'); 
    //give permission to the folder 
    chmod('C:/Users/ComputerName/Desktop/test', 0777); 
} 

//check whether the file exists 
if (file_exists('C:/Users/ComputerName/Desktop/test/'. $_FILES["file"]["name"])) 
{ 
    echo $_FILES["file"]["name"] . " already exists. "; 
} 
else 
{ 
    //move the file into the new folder 
    move_uploaded_file($_FILES["file"]["tmp_name"],'C:/Users/ComputerName/Desktop/test/'. $_FILES["file"]["name"]); 

} 

?> 

此外,您還可以從PHP服務器下載數據,並使用以下代碼在C#的Web瀏覽器中顯示它:

WebClient web = new WebClient(); 
try{ 
    byte[] response = web.DownloadData("http://" + ip +"/test.php"); 
    webBrowser1.DocumentText = System.Text.ASCIIEncoding.ASCII.GetString(response); 
} 
catch(Exception e) 
{ 
    MessageBox.Show("Download failed"); 
} 
+0

我試過這個。這隻會將文件上傳到php服務器。但我需要發送一個字符串與文件。讓字符串成爲文件夾的名稱,以便我可以識別應該保存哪個文件夾文件。 – MouseCrasher

+0

@MouseCrasher in web.UploadFile(「http://」+ ip +「/test.php」,StoreID);你可以發送字符串。您也可以上傳.zip文件,以便您也可以上傳字符串文件。 – aliboy38

+0

你是對的,但在我的情況只是看看代碼'Client.UploadFile(「http://localhost/upload.php」,「POST」,「C:\\ aaaa.jpg」); Client.UploadString(「http://localhost/upload.php」,「POST」,StoreID);'這些是兩個請求,我想只發送一個請求發送_aaaa.jpg_和_StoreID_ – MouseCrasher

0

您可以創建一個接受文件的PHP web服務。然後發佈該webservice,並將其添加到你的c#引用,然後在接受該文件的c#代碼中調用teh方法,並且vualá!

如何使用PHP創建SOAP link

+0

這是替代解決方案。但是,如果沒有網絡服務,它可能會發生嗎? – MouseCrasher

+0

不知道爲什麼你不想使用WS它會幫助你很多 – VicoMan

+0

當你的瀏覽器提交表單時,它不使用web服務。 @MouseCrasher試圖做的是重現這一點。 –

相關問題