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 に答える