【问题标题】:send file using HttpClient in PostAsync using function app in req.Form.Files c#使用 req.Form.Files 中的函数应用程序在 PostAsync 中使用 HttpClient 发送文件 c#
【发布时间】:2022-11-16 14:31:11
【问题描述】:

我创建了用于在 FTP 服务器上上传多个文件的 Function App。我已经收到所有使用req.Form.Files 的文件。但是当我收到请求时。我实际上是从 req.Body 中的 HttpClient 请求中找到我的文件的。当我在 Body->FormData 中从 Postman 上传文件时,它工作正常但现在我需要通过代码发送带有文件的发布请求。

我曾参考Sending a Post using HttpClient and the Server is seeing an empty Json file此链接尝试过以下代码。

HttpContent content = new StreamContent (stream);
content.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
HttpResponseMessage response = client.PostAsync ("url", content).Result;

但我想要文件在req.Form.Files 中。用户可能上传了多个文件或一个文件。

注意:现在我有一个由代码生成的文件。但它不应该保存在本地,所以我正在尝试发送流。在HttpContent

【问题讨论】:

  • 请更喜欢await而不是.Result

标签: c# file-upload azure-functions httprequest httpclient


【解决方案1】:

以下是使用函数应用程序进行异步后处理的步骤

 public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log)
        {
            string Connection = Environment.GetEnvironmentVariable("AzureWebJobsStorage");
            string containerName = Environment.GetEnvironmentVariable("ContainerName");
            var file = req.Form.Files["File"];**
            var filecontent = file.OpenReadStream();
            var blobClient = new BlobContainerClient(Connection, containerName);
            var blob = blobClient.GetBlobClient(file.FileName);
            byte[] byteArray = Encoding.UTF8.GetBytes(filecontent.ToString());

使用req.Form.Files 时的文件详细信息

已成功将文本文件上传到 blob 存储。

编辑:

这是使用 HttpClient 的 Post 请求

 var file = @"C:Users...Documents	est.txt";
        await using var stream = System.IO.File.OpenRead(file);
        using var request = new HttpRequestMessage(HttpMethod.Post, "file");
        using var content = new MultipartFormDataContent
         {
            { new StreamContent(stream),"File", "test.txt" }
         };
        request.Content = content;
        await client.SendAsync(request);
        return new OkObjectResult("File uploaded successfully");

【讨论】:

  • 我已经尝试从邮递员发送请求并且工作正常。我想从我的 C# 应用程序中调用这个函数应用程序。我正在发送请求。但我可以在 req.Body 中那个文件。我尝试使用 HttpRequestMessage。然后我在 req.Content 中找到了我的文件。你能告诉我如何使用 HttpClient 向这个功能应用程序发送请求吗?
  • 请检查编辑后的答案。
猜你喜欢
  • 1970-01-01
  • 2020-07-07
  • 1970-01-01
  • 2020-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-11
相关资源
最近更新 更多