0

I need to upload files (with different extensions ie .txt, .jpg, .pdf....) on a server. I created a site that accepts http requests an maps a virtual directory to a physical one. all thi works fine in dowload, now I have to implement the upload.

here is my code

private void UploadFile(string uploadFileName, string localFileName)
    {
        //long length = 0;
        string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
        HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(uploadFileName);
        httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
        httpWebRequest2.Method = "POST";
        httpWebRequest2.KeepAlive = true;
        httpWebRequest2.Credentials = new NetworkCredential("USER", "PASSWORD", "DOMAIN"); 

        Stream memStream = new System.IO.MemoryStream();

        byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +boundary + "\r\n");

        string formdataTemplate = "\r\n--" + boundary +"\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

        memStream.Write(boundarybytes, 0, boundarybytes.Length);

        string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";

        string header = string.Format(headerTemplate, "uplTheFile", localFileName);

        byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

        memStream.Write(headerbytes, 0, headerbytes.Length);

        FileStream fileStream = new FileStream(localFileName, FileMode.Open, FileAccess.Read);
        byte[] buffer = new byte[1024];

        int bytesRead = 0;

        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            memStream.Write(buffer, 0, bytesRead);
        }

        memStream.Write(boundarybytes, 0, boundarybytes.Length);

        fileStream.Close();

        httpWebRequest2.ContentLength = memStream.Length;

        Stream requestStream = httpWebRequest2.GetRequestStream();
        //error returned in lenght field: "This stream does not support seek operations."

        memStream.Position = 0;
        byte[] tempBuffer = new byte[memStream.Length];
        memStream.Read(tempBuffer, 0, tempBuffer.Length);
        memStream.Close();
        requestStream.Write(tempBuffer, 0, tempBuffer.Length);
        requestStream.Close();

        WebResponse webResponse2 = httpWebRequest2.GetResponse();
        //error returned from getResponse: "The remote server returned an error: (405) Method Not Allowed."
        //I guess cause my folder is in read only

        Stream stream2 = webResponse2.GetResponseStream();
        StreamReader reader2 = new StreamReader(stream2);

        MessageBox.Show(reader2.ReadToEnd());

        webResponse2.Close();
        httpWebRequest2 = null;
        webResponse2 = null; 

    }

firstly I got this error: The remote server returned an error: (405) Method Not Allowed. so I tried to enable POST by adding a mapping onto the web site.

now in the folder on te server I have a web.config file that is:

    <?xml version="1.0" encoding="UTF-8"?>
 <configuration>
    <system.webServer>
    <directoryBrowse enabled="true" />
    <handlers>
        <add name="File TXT" path="*.*" verb="*" modules="IsapiModule" scriptProcessor="C:\Windows\System32\inetsrv\asp.dll" resourceType="Unspecified" requireAccess="Script" preCondition="bitness64" />
    </handlers>
</system.webServer>
</configuration>

in this way I do not get any error, but the application does not upload any file. how do I solve this problem?

andrea
  • 1,326
  • 7
  • 31
  • 60
  • Can't you just save the file? Are you using the Asp.NET file upload control? Do you need to send the file across to another endpoint? – awright18 Oct 24 '12 at 09:49
  • what do you mean by "just save the file"? I need to upload it from client to server folder. no I'm not using Asp.NET, just a web site in the application pool which is called from client by the httpwebrequest (not sure if I completly answer your question) – andrea Oct 24 '12 at 09:52

2 Answers2

0

A much simpler solution would be to use the System.Net.Webclient class to upload the file.

System.Net.WebClient client = new System.Net.WebClient();

client.UploadFile("www.myfileuploadendpoint.com",@"c:\myfiletoupload.txt");

The client also has an OnUploadFileCompleted event that will call a handler when its done.

client.OnUploadFileCompleted  += UploadCompleted(sender,args) => { //do whatever you want}

This will save you code and bugs. Good Luck! :)

awright18
  • 2,255
  • 2
  • 23
  • 22
  • Got exactly the same behaviour. 1) POST not allowed, and after adding the web.confing no error but no file uploaded – andrea Oct 24 '12 at 10:12
  • Thought this may be relevant http://stackoverflow.com/questions/2436182/405-method-not-allowed-error-in-wcf – awright18 Oct 24 '12 at 10:15
  • "GET" says it is a wron verb and actually is quite expected. I think I need POST to upload files or data in general – andrea Oct 24 '12 at 10:36
-1

Both of the above sample not working,

  1. "The remote server returned an error: (405) Method Not Allowed." is the exception caught on trying both the above codes

Expect someone to share their thought on these exceptions, Please.

rgds, thiru