繁体   English   中英

在单个HTTPWebRequest中上载多个文件

[英]Upload multiple files in a single 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-dataapplication / 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);
    }

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

您上面的代码不会创建正确的多部分正文。

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

请参阅使用HTTPWebrequest上传文件(multipart / form-data)

有关您的多个contentTypes问题的一些信息: http//www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.2

multipart / form-data是通过http协议发送多个数据类型的唯一方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM