【问题标题】:Upload multiple files in a single HTTPWebRequest在单个 HTTPWebRequest 中上传多个文件
【发布时间】:2013-02-26 10:43:32
【问题描述】:

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

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

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

【问题讨论】:

  • multipart /form-data 已经是 multiple 内容类型(文件和表单数据)的标头。你不应该需要 application/x-www-form-urlencoded
  • 但它对我不起作用,在服务器端我没有得到任何文件,或者你可以说流。

标签: c# wcf web-services rest fiddler


【解决方案1】:

您上面的代码没有创建正确的多部分正文。

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

Upload files with HTTPWebrequest (multipart/form-data)

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-11-17
      • 2019-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-23
      • 1970-01-01
      • 2010-12-13
      • 2013-10-12
      相关资源
      最近更新 更多