【问题标题】:How can I upload a CSV file as a stream using HttpClient as a body parameter?如何使用 HttpClient 作为正文参数将 CSV 文件作为流上传?
【发布时间】:2019-05-22 12:18:14
【问题描述】:

我正在尝试使用以下代码将 csv 文件转换为 contentStream。

private const string ResourceFolder = "TestData\\";
private HttpContent _form;

      public void SendFile(string resource, string fileName)
    {
        _form = string.IsNullOrWhiteSpace(fileName)
            ? _form = new StringContent(string.Empty)
            : _form = new StreamContent(File.OpenRead($"{ResourceFolder}{fileName}"));

        var content = new MultipartFormDataContent();
           content.Add(_form);
        _form.Headers.ContentType = new MediaTypeHeaderValue("application/csv");

        WhenThePostRequestExecutesWithContent(resource, content);

    }

    public async void WhenThePostRequestExecutesWithContent(string resource, HttpContent content)
    {
        ResponseMessage = await HttpClient.PostAsync(resource, content);
    }

我正在使用.Net core 2.1,它在File 位置的最后一行给出以下错误

问题是我仍然发现下面的控制器文件参数为空,

控制器:

public async Task<IActionResult> SeedData(IFormFile file)
{
    var result = await _seedDataService.SeedData(file);
    return Ok(new { IsUploadSuccesful = result});
}

【问题讨论】:

  • 编译器将File 解析为System.IO.File,因为File 方法的重载不匹配您的参数(Stream, string, Stream)。为什么你认为你需要MemoryStream,在这里?
  • 有什么理由不能直接流式传输 CSV 文件? File($"{ResourceFolder}{fileName}", "text/csv") 应该足够了。您现在拥有的代码实际上并没有对内存流做任何事情。如果您想将文件读入流中以进行额外处理,您将需要比现在更多的代码(然后您可以返回 MemoryStream)。
  • @SMPH 该错误与流无关。这意味着您正在尝试在控制器外部使用 Controller 方法。在控制器操作中,返回存储在磁盘上的文件唯一需要做的就是return File(pathToFile);
  • @SMPH 你不能只是复制代码并希望它有效。这不仅仅是你不需要那个流。 StreamContent 接受任何流。您可以使用简单的File.OpenRead() 打开 FileStream。您已使用 "application/json" 作为 CSV 文件的内容类型。

标签: c# stream httpclient


【解决方案1】:

感谢大家的贡献,下面的代码解决了这个问题。

private const string ResourceFolder = "TestData\\";
private HttpContent _form;

     public void AttachedRatesFile(string fileName)
        {
            _form = string.IsNullOrWhiteSpace(fileName)
                ? _form = new StringContent(string.Empty)
                : _form = new StreamContent(File.OpenRead($"{ResourceFolder}{fileName}"));

            _content = new MultipartFormDataContent();
            _content.Add(_form, "file", fileName);
            _form.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

        }


    public async void WhenThePostRequestExecutesWithContent(string resource, HttpContent content)
    {
        ResponseMessage = await HttpClient.PostAsync(resource, content);
    }

【讨论】:

    猜你喜欢
    • 2013-12-08
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多