2011-09-14 31 views
0

我想將文件上傳到服務器。我寫了這個功能把文件上傳到本地主機服務器(我使用WAMP服務器):使用Httpwebrequest上傳文件

private void button1_Click_1(object sender, EventArgs e) 
    { 
     FileStream fstream = new FileStream(@"C:\Users\Albert\Documents\10050409_3276.doc", FileMode.OpenOrCreate); 
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/upload_file"); 
     request.Method = "PUT"; 
     request.ContentLength = fstream.Length; 
     request.AllowWriteStreamBuffering = true; 
     Stream request_stream = request.GetRequestStream(); 
     byte[] indata = new byte[1024]; 
     int bytes_read = fstream.Read(indata, 0, indata.Length); 
     while (bytes_read > 0) 
     { 
      request_stream.Write(indata, 0, indata.Length); 
      bytes_read = fstream.Read(indata, 0, indata.Length); 
     } 
     fstream.Close(); 
     request_stream.Close(); 
     request.GetResponse(); 
     MessageBox.Show("ok"); 
    } 

因此,當我點擊按鈕除外衝擊片雷管說:

Additional information: The remote server returned an error: (405) Method Not Allowed.

我試圖用「POST」而不是「PUT」,所以程序工作和消息框似乎說'好',但是當我打開localhost-> upload_file(文件夾)Ididn't找到任何文件。

我用wamp server =>測試了我的程序,發生了問題。

我用真實服務器測試了我的程序,並放入了網絡憑據,並試圖上傳到具有(777)權限的文件夾 - >出現問題。

那麼問題到底在哪裏呢?

謝謝:)

+0

這是C#代碼,對不對? –

+0

是的它是C#代碼 – Albert

+0

我認爲你錯過了Multipart Mime類型。除非您專門創建了允許使用「PUT」方法的網站,否則您一定需要使用「POST」。 –

回答

2

嘗試用Web客戶端

WebClient client = new WebClient(); 
byte[] bret = client.UploadFile(path, "POST", FilePath); 
//path==URL 
//FilePath==Your uploading file path 

WebClient webClient = new WebClient(); 
string webAddress = null; 
try 
{ 
    webAddress = @"http://localhost/upload_file/"; 

    webClient.Credentials = CredentialCache.DefaultCredentials; 

    WebRequest serverRequest = WebRequest.Create(webAddress); 
    serverRequest.Credentials = CredentialCache.DefaultCredentials; 
    WebResponse serverResponse; 
    serverResponse = serverRequest.GetResponse(); 
    serverResponse.Close(); 

    webClient.UploadFile(path, "POST", FilePath); 
    webClient.Dispose(); 
    webClient = null; 
} 
catch (Exception error) 
{ 
    MessageBox.Show(error.Message); 
} 

(或部分代碼,我也沒試過)

+0

WebClient客戶端=新的WebClient(); byte [] bret = client.UploadFile(「http:// localhost/Lecture Fetcher/xml_files」,「POST」,「k.xml」); Console.WriteLine(「ok」); – Albert

+0

CONSOL寫(確定),但是當我打開xml_files(文件夾)沒有任何文件存在 – Albert

+0

嘗試更新代碼 – deepi