2011-09-14 40 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

相关问题