简体   繁体   English

在 Req.Form.Files c# 中使用 function 应用程序在 PostAsync 中使用 HttpClient 发送文件

[英]send file using HttpClient in PostAsync using function app in req.Form.Files c#

I have created Function App for uploading multiple files on FTP server.我创建了 Function 应用程序,用于在 FTP 服务器上上传多个文件。 I have received all files using req.Form.Files .我已经使用req.Form.Files收到了所有文件。 but When I get the request.但是当我收到请求时。 I actually found my file from HttpClient request in req.Body .我实际上在req.Body中从HttpClient请求中找到了我的文件。 When I upload file from Postman in Body->FormData it, works fine but now I need to send post request with file by code.当我在 Body->FormData 中从 Postman 上传文件时,它工作正常但现在我需要通过代码发送带有文件的发布请求。

I had tried below code with reference of Sending a Post using HttpClient and the Server is seeing an empty Json file this link.我已尝试使用以下代码参考使用 HttpClient 发送帖子,并且服务器在此链接中看到一个空的 Json 文件

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

But I want file in req.Form.Files .但我想要req.Form.Files中的文件。 Where user might have uploaded multiple files or one file.用户可能上传了多个文件或一个文件。

Note: For now I have a file which is being generated by code.注意:现在我有一个由代码生成的文件。 But it should not be saved on local so I'm trying to send stream. in HttpContent但它不应该保存在本地所以我试图发送 stream. 在HttpContent

Below are the steps for Post Async using function app以下是使用 function 应用程序进行异步发布的步骤

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

File details while using req.Form.Files使用req.Form.Files时的文件详细信息

在此处输入图像描述

Successfully uploaded a text file to blob storage.已成功将文本文件上传到 blob 存储。

在此处输入图像描述

Edit :编辑

Here is the Post request Using HttpClient这是使用 HttpClient 的 Post 请求

 var file = @"C:\Users\...\Documents\test.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");

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

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