1

嗨,我需要在 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 框架中给出响应

等待您的建议

4

1 回答 1

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 正文添加其他简单参数,您可能需要手动执行此操作。我在博客上写了一个可以在这种情况下使用的示例类。

于 2012-08-18T09:54:04.153 回答