0

我想使用我的 Windows 应用程序将多个图像文件上传到 Web 服务器。这是我的代码

     public void UploadMyFile(string URL, string localFilePath)
    {
      HttpWebRequest req=(HttpWebRequest)WebRequest.Create(URL);                     
      req.Method = "PUT";
      req.AllowWriteStreamBuffering = true;

      // Retrieve request stream and wrap in StreamWriter
      Stream reqStream = req.GetRequestStream();
      StreamWriter wrtr = new StreamWriter(reqStream);

      // Open the local file
      StreamReader rdr = new StreamReader(localFilePath);

      // loop through the local file reading each line 
      //  and writing to the request stream buffer
      string inLine = rdr.ReadLine();
      while (inLine != null)
      {
        wrtr.WriteLine(inLine);
        inLine = rdr.ReadLine();
      }

      rdr.Close();
      wrtr.Close();

      req.GetResponse();
    }

我参考了以下链接 http://msdn.microsoft.com/en-us/library/aa446517.aspx

我收到异常远程服务器返回了意外响应:(405)方法不允许。

4

1 回答 1

1

当这些是图像文件时,您为什么要按行读取和写入?您应该以字节块的形式进行读写。

public void UploadMyFile(string URL, string localFilePath)
{
      HttpWebRequest req=(HttpWebRequest)WebRequest.Create(URL);

      req.Method = "PUT";
      req.ContentType = "application/octet-stream";

      using (Stream reqStream = req.GetRequestStream()) {

          using (Stream inStream = new FileStream(localFilePath,FileMode.Open,FileAccess.Read,FileShare.Read)) {
              inStream.CopyTo(reqStream,4096);
          }

          reqStream.Flush();
      }

      HttpWebResponse response = (HttpWebReponse)req.GetResponse();
}

您也可以尝试更简单的WebClient方法:

public void UploadMyFile(string url, string localFilePath)
{
    using(WebClient client = new WebClient()) {
        client.UploadFile(url,localFilePath);
    }
}
于 2013-03-06T10:29:46.327 回答