Reputation: 331
I want to upload multiple image file to the web server using my windows application. Here is my code
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();
}
I referred the following link http://msdn.microsoft.com/en-us/library/aa446517.aspx
I am getting exception The remote server returned an unexpected response: (405) Method not allowed.
Upvotes: 0
Views: 4971
Reputation: 29668
Why are you reading and writing in terms of lines when these are image files? You should be reading and writing in blocks of bytes.
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();
}
You could also try the much simpler WebClient
way:
public void UploadMyFile(string url, string localFilePath)
{
using(WebClient client = new WebClient()) {
client.UploadFile(url,localFilePath);
}
}
Upvotes: 1