c# – 在单个HTTPWebRequest中上传多个文件

我创建了一个接受两件事的服务:

1)称为“类型”的身体参数.

2)要上传的csv文件.

我在服务器端读这两样东西是这样的:

 //Read body params
 string type = HttpContext.Current.Request.Form["type"];

 //read uploaded csv file
 Stream csvStream = HttpContext.Current.Request.Files[0].InputStream;

我怎么能测试这个,我使用Fiddler来测试这个,但我一次只能发送一件事(无论是类型还是文件),因为两者都是不同的内容类型,我如何使用内容类型multipart / form-data和application / x-www-form-urlencoded同时进行.

即使我使用此代码

    public static void PostDataCSV()
    {
        //open the sample csv file
        byte[] fileToSend = File.ReadAllBytes(@"C:\SampleData.csv"); 

        string url = "http://localhost/upload.xml";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "multipart/form-data";
        request.ContentLength = fileToSend.Length;


        using (Stream requestStream = request.GetRequestStream())
        {
            // Send the file as body request. 
            requestStream.Write(fileToSend, 0, fileToSend.Length);
            requestStream.Close();
        }

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        //read the response
        string result;
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            result = reader.ReadToEnd();
        }

        Console.WriteLine(result);
    }

这也不会向服务器发送任何文件.

最佳答案 您上面的代码不会创建正确的多部分正文.

您不能简单地将文件写入流中,每个部分都需要带有每个部分标题的前导边界标记等.

Upload files with HTTPWebrequest (multipart/form-data)

点赞