使用Httpwebrequest上传文件

时间:2011-09-14 05:51:19

标签: c# html

我想将文件上传到服务器。我写了这个函数来将文件上传到localhost服务器(我使用的是wamp服务器):

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");
    }

所以当我点击按钮时,异常apper说:

  

其他信息:远程服务器返回错误:(405)Method Not Allowed。

我尝试使用“POST”而不是“PUT”,因此程序正常工作,消息框显示为“ok”,但是当我打开localhost-> upload_file(文件夹)时,我找不到任何文件。

我用wamp server =>测试了我的程序问题出现了。

我使用真实服务器测试了我的程序并输入了网络凭据并尝试上传到具有(777)权限=>的文件夹问题出现了。

那么问题究竟在哪里?

谢谢:)

1 个答案:

答案 0 :(得分:2)

尝试使用webClient

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); 
} 

(代码或部分我没有尝试过)