I am trying to upload file in web server as following using C#
try
{
// create WebClient object
WebClient client = new WebClient();
string myFile = @"D:\test_file.txt";
client.Credentials = CredentialCache.DefaultCredentials;
// client.UploadFile(@"http://mywebserver/myFile", "PUT", myFile);
client.UploadFile(@"http://localhost/uploads", "PUT", myFile);
client.Dispose();
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
But every time I am getting this error:
The remote server returned an error: (405) Method Not Allowed.
REST API File Upload with Java In the above code block, we have created an endpoint of type HTTP Post that is waiting for file. This endpoint prints the name of the external file to the console of the application. That's all we'll do for File Upload on the code side.
I have solved this using the POST method and server side code:
C# code
try
{
WebClient client = new WebClient();
string myFile = @"D:\test_file.txt";
client.Credentials = CredentialCache.DefaultCredentials;
client.UploadFile(@"http://localhost/uploads/upload.php", "POST", myFile);
client.Dispose();
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
Server side PHP code upload.php
<?php
$filepath = $_FILES["file"]["tmp_name"];
move_uploaded_file($filepath,"test_file.txt");
?>
The error means that the "PUT" method you are using is not allowed by the server. Check the response headers for allowed methods. More info here.
Or check the documentation for the application to which you are trying to upload the file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With