1

Hi i need to send the file name and a file as parameters in http post method i used following code as

string reponseAsString = "";
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[8192];


    ServicePointManager.ServerCertificateValidationCallback += delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        return true;
    };
    string fileToUpload = filepath;
    FileStream rdr = new FileStream(fileToUpload, FileMode.Open);
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); //Given URI is exists
    req.Method = "POST";
    req.ContentLength = rdr.Length;
    req.AllowWriteStreamBuffering = true;
    Stream reqStream = req.GetRequestStream();
    Console.WriteLine(rdr.Length);
    byte[] inData = new byte[rdr.Length];

    // Get data from upload file to inData 
    int bytesRead = rdr.Read(inData, 0, (int)rdr.Length);

    // put data into request stream
    reqStream.Write(inData, 0, (int)rdr.Length);
    rdr.Close();

    // req.GetResponse();
    HttpWebResponse response = (HttpWebResponse)req.GetResponse();

    Stream resStream = response.GetResponseStream();
    string tempString = null;
    int count = 0;

    do
    {
        count = resStream.Read(buf, 0, buf.Length);
        if (count != 0)
        {
            tempString = Encoding.ASCII.GetString(buf, 0, count);
            sb.Append(tempString);

        }
    }

    while (count > 0);


    reponseAsString = sb.ToString();
    reqStream.Close();
}

Here i just send the url and file path with file name as request but required response does not obtained.. but when it run through advanced client it give response in c# .net4 framework

Waiting for your sugessions

1 Answer 1

2

You could use multipart/form-data request encoding. I guess that's what your server expects. So:

string fileToUpload = @"c:\work\somefile.jpg";
string url = "http://foo.com/upload";
using (var client = new WebClient())
{
    byte[] result = client.UploadFile(url, fileToUpload);
    string responseAsString = Encoding.Default.GetString(result);
}

But this is limited to a single file only. If you needed to upload more than one file or add other simple parameters to the POST body you might need to manually do that. I've blogged about a sample class that could be used in this case.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.