将文件发送为httprequest c#.net

时间:2012-08-18 09:49:15

标签: c# .net httpwebrequest

您好我需要在http post方法中将文件名和文件作为参数发送,我使用以下代码作为

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();
}

这里我只是发送带文件名的url和文件路径作为请求,但是没有获得所需的响应..但是当它通过高级客户端运行时,它在c#.net4框架中给出响应

等待你的sugessions

1 个答案:

答案 0 :(得分:2)

您可以使用multipart/form-data请求编码。我猜这就是你的服务器所期望的。所以:

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);
}

但这仅限于一个文件。如果您需要上传多个文件或将其他简单参数添加到POST正文,则可能需要手动执行此操作。我blogged about a sample class可以在这种情况下使用。