Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File upload to web server using C#

Tags:

c#

webclient

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.

like image 362
MaxEcho Avatar asked Jun 27 '15 07:06

MaxEcho


People also ask

Can we upload file using REST API?

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.


2 Answers

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");
?>
like image 183
MaxEcho Avatar answered Sep 22 '22 15:09

MaxEcho


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.

like image 45
Kumar Avatar answered Sep 22 '22 15:09

Kumar