I want to upload file to a server. I wrote this function to upload the file to localhost server (I am using wamp server):
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");
}
So when i click on the button the exception apper said that:
Additional information: The remote server returned an error: (405) Method Not Allowed.
I tried to use "POST" instead of "PUT" so the program works and the message box appears to say 'ok', but when i open the localhost->upload_file(folder) Ididn't find any files.
I tested my program with wamp server => the problem occured.
I tested my program with real server and put in the network credentials and tried to upload to 开发者_如何学编程folder that has (777) permission => the problem occured.
So where is the problem exactly?
Thanks :)
try with webClient
WebClient client = new WebClient();
byte[] bret = client.UploadFile(path, "POST", FilePath);
//path==URL
//FilePath==Your uploading file path
or
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);
}
(code in or part i didn't tried )
精彩评论