0

I'm trying to figure out how to upload a file using C# on a

<input type="file" />

I've been testing my code out with this sample upload form http://cgi-lib.berkeley.edu/ex/fup.html.

Here's my code which I took from this answer: https://stackoverflow.com/a/2996904/2245648.

    static void Main(string[] args)
    {
        NameValueCollection nvc = new NameValueCollection();
        nvc.Add("tbxEmail", "test");
        nvc.Add("btn-submit-photo", "Upload");
        HttpUploadFile(@"http://jobview.monster.ca/Apply/Apply.aspx?JobID=133227319",
             @"C:\test\test.jpg", "file", "image/jpeg", nvc);
        Console.ReadLine();
    }



    public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
    {
        Console.WriteLine(string.Format("Uploading {0} to {1}", file, url));
        string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
        byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

        HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
        wr.ContentType = "multipart/form-data; bsundary=" + boundary;
        wr.Method = "POST";
        wr.KeepAlive = true;
        wr.Credentials = System.Net.CredentialCache.DefaultCredentials;

        Stream rs = wr.GetRequestStream();

        string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
        foreach (string key in nvc.Keys)
        {
            rs.Write(boundarybytes, 0, boundarybytes.Length);
            string formitem = string.Format(formdataTemplate, key, nvc[key]);
            byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
            rs.Write(formitembytes, 0, formitembytes.Length);
        }
        rs.Write(boundarybytes, 0, boundarybytes.Length);

        string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
        string header = string.Format(headerTemplate, paramName, file, contentType);
        byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
        rs.Write(headerbytes, 0, headerbytes.Length);

        FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
        byte[] buffer = new byte[4096];
        int bytesRead = 0;
        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            rs.Write(buffer, 0, bytesRead);
        }
        fileStream.Close();

        byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
        rs.Write(trailer, 0, trailer.Length);
        rs.Close();

        WebResponse wresp = null;
        try
        {
            wresp = wr.GetResponse();
            Stream stream2 = wresp.GetResponseStream();
            StreamReader reader2 = new StreamReader(stream2);
            Console.WriteLine(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd()));
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error uploading file", ex);
            if (wresp != null)
            {
                wresp.Close();
                wresp = null;
            }
        }
        finally
        {
            wr = null;
        }
    }

I don't know what to put in nvc.Add(), I thought it would be the name of the element? How would this work if I were uploading a file to cgi-lib.berkeley.edu? I look at my result and I get the same exact page again. I was assuming I would get the confirmation page display my file contents.

EDIT:

Does WebClient supports multipart/form-data?

Community
  • 1
  • 1
Jason
  • 259
  • 2
  • 12
  • 1
    If you just need to upload a file to some server via `POST` without headers, then you can just use `WebClient.UploadFile` that will be much easier - http://msdn.microsoft.com/library/36s52zhs(v=vs.110).aspx . That page has a sample of usage. – Sergey Litvinov May 03 '14 at 20:41
  • 1
    To know what to put inside of your method, you must see how is it use. But I am not sure you will succeed as for your sample it uses a textbox with the name of the file. And then via the method `HttpUploadFile` they provide the source of the file. Otherwise you should have first something like this Let's say your input is like this `` and then nvc.Add("myFile","here it supposed to be the value, a string"); just do as @SergeyLitvinov proposes you –  May 03 '14 at 21:00

0 Answers0