【问题标题】:How so send multiple files in MultipartFormDataContent?如何在 MultipartFormDataContent 中发送多个文件?
【发布时间】:2019-08-09 18:26:09
【问题描述】:

我想将多个文件添加到我的多部分表单数据中。我在我的 WPF 客户端应用程序中执行了以下操作,但不确定这是否正确

    public string UploadFiles(string type, string[] files)
    {
        string result = string.Empty;

        string url = "http://localhost/api/Utilities/Upload/" + type;

        MultipartFormDataContent form = new MultipartFormDataContent();
        form.Add(new StringContent("value"), "category");
        form.Add(new StringContent("value"), "source");
        form.Add(new StringContent("value"), "enteredby");
        foreach (string file in files)
        {
            FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
            var fileContent = new StreamContent(fileStream);
            fileContent.Headers.Add("Content-Type", "application/octet-stream");
        }

        var response = client.PostAsync(url, form);

        return result;
    }

在我的 ASP>NET Web Api 控制器中,我阅读了这样的内容

        string source = System.Web.HttpContext.Current.Request.Form.Get("source");
        string category = System.Web.HttpContext.Current.Request.Form.Get("category");
        string enteredby = System.Web.HttpContext.Current.Request.Form.Get("enteredby");

        System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;

我可以获取第一个值,但是如何获取我添加的文件? 还有一种方法可以将文件包含在表单中,以便可以从System.Web.HttpContext.Current.Request.Files访问它们

【问题讨论】:

    标签: c# asp.net .net asp.net-web-api


    【解决方案1】:

    我没有看到您实际上已将“StreamContent”添加到您创建的“表单”变量中。在你的 for 循环中,写:-

    FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
    var fileContent = new StreamContent(fileStream);
    fileContent.Headers.Add("Content-Type", "application/octet-stream");
    form.Add(fileContent);
    

    【讨论】:

      猜你喜欢
      • 2018-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-16
      • 2020-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多