locked
File upload by WebClient RRS feed

  • Question

  • Hi all,
    I need to upload file and send two strings to server by POST method, using WebClient. In HTML it looks something like that:

    <form action="http://127.0.0.1:8080/avatarupload" method="POST" enctype="multipart/form-data"> 
        <input type="hidden" name="data1" value="1032">
        <input type="hidden" name="data2" value="4020">
        <input type="file" name="file" size="40">
        <input type="submit" value="Send">
    </form>

    I need to also, after data sending, receive server response

    How can do it in C#?

    Thanks for any reply
    • Edited by raf-t Thursday, September 6, 2012 7:06 AM
    Thursday, September 6, 2012 7:05 AM

All replies

  • WebClient wc = new WebClient();
    
    //remember to create a DownloadStringCompleted listener
    wc.DownloadStringAsync(new Uri("http://qwerty.ui?paramOne=hey&paramTwo=yoo"));
    
    
    .....
    DownloadComoleted(object sender ....
    String results = e.result;

    This is as easy as 3.141592653 ;)

    If you need another method for doing it just tell me and Ill help you out!

    Best regards,

    Harold (Zumicts Founder/CEO)

    Thursday, September 6, 2012 10:30 AM
  • Zumicts answer will work if you have access to the server and look in the QueryString instead of the Form POST data.

    However, if you want to use POST to upload data as your post asked, you can try this:

    var request = (HttpWebRequest)WebRequest.Create("http://example.com"); 
            request.ContentType = "multipart/form-data; boundary=" + boundary; 
            request.Method = "POST"; 
     
            using (var requestStream = request.GetRequestStream()) 
            using (var writer = new StreamWriter(requestStream)) 
            {
                /// Send Data1
                writer.WriteLine(boundary);
                writer.WriteLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", "data1")); 
                writer.WriteLine(); 
                writer.WriteLine(data1.ToString()); 
    
                /// And, now Data2
                writer.WriteLine(boundary);
                writer.WriteLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", "data2")); 
                writer.WriteLine(); 
                writer.WriteLine(data2.ToString());             
                /// and now the file data.  adjust filename and 
                /// content type to match what you are uploading.
                writer.WriteLine(boundary);
                writer.WriteLine(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"", "file", "test.txt")); 
                writer.WriteLine(string.Format("Content-Type: {0}", "text/plain");
               writer.WriteLine(); 
               writer.Write(binaryFileData, 0, binaryFileData.Length());
    
                writer.WriteLine(boundary + "--"); 
            } 
    
    Check out the multipart-form data specifications if you have questions about that.

    Darin R.

    Thursday, September 6, 2012 12:14 PM
  • Ok, thanks for Your answer

    But by DownloadStringAsync I can only send text parameters by GET method. I have to send data by POST method, and not only text but also binary file.

    Please, look at this code:

    private const string url = "https://mydomain.net/upload.ashx";
    
    private const string authorizationLogin = "myuser";
    private const string authorizationPassword = "mypassword";
    private static string parameters = "data1=1032&data2=4020&file=";
    
    private void SendDataByPost(byte[] file)
    {
        WebClient webClient = new WebClient();
        webClient.Credentials = new System.Net.NetworkCredential(authorizationLogin, authorizationPassword);
        webClient.UploadStringCompleted += new UploadStringCompletedEventHandler
        (
            delegate(object sender, UploadStringCompletedEventArgs e)
            {
                if (e.Error == null)
                {
                    webClient.OpenWriteAsync(new Uri(url, UriKind.Absolute));
                }
            }
        );
        webClient.OpenWriteCompleted += new OpenWriteCompletedEventHandler
        (
            delegate(object sender, OpenWriteCompletedEventArgs e)
            {
                if (e.Error == null)
                {
                    Stream writeStream = e.Result;
                    writeStream.Write(file, 0, file.Length);
                    writeStream.Flush();
                    writeStream.Close();
                }
            }
        );
        webClient.WriteStreamClosed += new WriteStreamClosedEventHandler 
        (
            delegate(object s, WriteStreamClosedEventArgs e)
            {
                if (e.Error == null)
                    MessageBox.Show("Upload Complete");
                else
                    MessageBox.Show(e.Error.Message);
    
                //how can i read server response here?
            }
        );
    
        webClient.UploadStringAsync(new Uri(url, UriKind.Absolute), parameters);
    }

    I use UploadStringAsync to send text parameters, and then run OpenWriteAsync to send binary file. Is it ok?

    And how can I read server response after file sending in WriteStreamClosed event?

    Thursday, September 6, 2012 12:17 PM