分段数据上传 - Azure Function V2

Multipart Data Upload - Azure Function V2

正在将文档上传到 HTTP 触发器 Azure 函数(版本 2)。在我的函数中收到请求后,我看到文件部分为空,流被移动到 formdata 字典。下面是如何上传文档的代码,有人可以帮助我为什么它不填充 IFormFileCollection 中的流。


      using (var _httpClient = new HttpClient())
            {
                MultipartFormDataContent form = new MultipartFormDataContent();
                String headerValue = "form-data; name=\"file\"; filename=\"" + fileName + "\"";
                byte[] bytes = Encoding.UTF8.GetBytes(headerValue);
                headerValue = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
                fileContent.Headers.Add("Content-Disposition", headerValue);
                fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
                form.Add(fileContent);
                form.Add(new StringContent(metadataValue), metadataKey);
                _httpClient.Timeout = TimeSpan.FromMinutes(15);
                _httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + bearerToken);
                logger.LogInformation($"HttpUtils: UploadFileByMultipart() url:{url}, request param: {metadataValue} reference: {traceLogId}");
                var response = await _httpClient.PostAsync(url, form).Result.Content.ReadAsStringAsync();
                logger.LogInformation("HttpUtils: UploadFileByMultipart() end");
                return response;
            }

Content received in Function

其他请注意如何从字符串格式的 Formdata 字典中获取流并将其转换为我可以播放的流。我在下面尝试过,结果是一个空白文档,破坏了所有流

        requestHandler.stream = new MemoryStream();
        var Content = formdata["file"].ToString();
        var fileContent = new MemoryStream(Encoding.ASCII.GetBytes(Content));

如果我们想用HttpClient发送Multipart Data,可以用MultipartFormDataContent创建数据。

例如

我发送请求的代码

MultipartFormDataContent form = new MultipartFormDataContent();

            form.Add(new StringContent("jack"), "userName");

            var fileContent = new ByteArrayContent(File.ReadAllBytes(@"D:\my.csv"));

            // I use package MimeMapping : https://www.nuget.org/packages/MimeMapping/ to get file mine type
            fileContent.Headers.ContentType = new MediaTypeHeaderValue(MimeUtility.GetMimeMapping("my.csv"));
            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                Name = "file",
                FileName = "my.csv"
            };
            form.Add(fileContent);

            using (var client = new HttpClient())
            {
                var res = await client.PostAsync("<function app url>", form);
                if (res.IsSuccessStatusCode)
                {
                    var content = await res.Content.ReadAsStringAsync();
                    Console.WriteLine(content);

                }

            }
  1. 我的函数应用代码
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
  ILogger log)
{
            log.LogInformation("C# HTTP trigger function processed a request.");

            log.LogInformation("-------------------read file----------------------");
            // read file
            var files = req.Form.Files;
            if (files.Count != 0) {
                var file = files[0];
                
                log.LogInformation(file.ContentType);
                log.LogInformation(file.FileName);
                log.LogInformation(file.ContentDisposition);
                // use file.OpenReadStream to get a stream then use stream to rread file content

            }

            // read key

            log.LogInformation("-------------------read key----------------------");
            log.LogInformation($"The userName is {req.Form["userName"]}");

            return new OkObjectResult("OK");
}