簡體   English   中英

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

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

我創建了 Function 應用程序,用於在 FTP 服務器上上傳多個文件。 我已經使用req.Form.Files收到了所有文件。 但是當我收到請求時。 我實際上在req.Body中從HttpClient請求中找到了我的文件。 當我在 Body->FormData 中從 Postman 上傳文件時,它工作正常但現在我需要通過代碼發送帶有文件的發布請求。

我已嘗試使用以下代碼參考使用 HttpClient 發送帖子,並且服務器在此鏈接中看到一個空的 Json 文件

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

但我想要req.Form.Files中的文件。 用戶可能上傳了多個文件或一個文件。

注意:現在我有一個由代碼生成的文件。 但它不應該保存在本地所以我試圖發送 stream. 在HttpContent

以下是使用 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());

使用req.Form.Files時的文件詳細信息

在此處輸入圖像描述

已成功將文本文件上傳到 blob 存儲。

在此處輸入圖像描述

編輯

這是使用 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