使用Httpwebrequest上传文件

本文关键字:文件 Httpwebrequest 使用 | 更新日期: 2023-09-27 18:08:36

我想上传文件到服务器。我写了这个函数来上传文件到本地主机服务器(我使用的是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");
    }

所以当我点击按钮的时候异常提示说:

附加信息:远程服务器返回一个错误:(405)Method Not Allowed.

我试图使用"POST"而不是"PUT",所以程序工作,消息框似乎说"ok",但是当我打开localhost->upload_file(文件夹)时,我没有找到任何文件。

我在wamp服务器上测试了我的程序=>问题出现了。

我在真实服务器上测试了我的程序,并输入了网络凭据,并试图上传到具有(777)权限的文件夹=>问题发生了

那么问题到底在哪里呢?

谢谢

使用Httpwebrequest上传文件

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