【问题标题】:Uploading file using Httpwebrequest使用 Httpwebrequest 上传文件
【发布时间】:2012-05-04 22:29:43
【问题描述】:

我想上传文件到服务器。我写了这个函数来上传文件到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");
    }

所以当我点击按钮时,异常显示:

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

我尝试使用“POST”而不是“PUT”,因此程序可以运行,并且消息框似乎显示“ok”,但是当我打开 localhost->upload_file(folder) 时,我没有找到任何文件。

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

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

那么问题到底出在哪里?

谢谢:)

【问题讨论】:

  • 我认为您缺少 Multipart Mime 类型。除非您专门创建了一个允许“PUT”方法的网站,否则您肯定需要使用“POST”。

标签: c# html


【解决方案1】:

尝试使用 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); 
} 

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

【讨论】:

  • WebClient 客户端 = new WebClient(); byte[] bret = client.UploadFile("localhost/Lecture Fetcher/xml_files", "POST", "k.xml"); Console.WriteLine("ok");
  • consol write (ok) 但是当我打开 xml_files (文件夹) 时没有任何文件存在
  • 一切正常,但上传文件(floder)中不存在任何文件
  • 尝试使用文件:FileInfo fileInfo = new FileInfo(Server.MapPath(filePath)); fileInfo.CopyTo(路径);
猜你喜欢
  • 2012-03-02
  • 1970-01-01
  • 2010-12-13
  • 2013-08-04
  • 1970-01-01
  • 2010-10-18
  • 2011-11-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多