将 json 和文件发送到 Azure Function

问题描述 投票:0回答:1

我正在尝试将文件上传到 Azure 函数,但我还需要一个 json 对象来添加附加上下文,但我很困惑。

我不确定是否是 VS Code 中的 RestClient 出现了问题,或者是 Azure 功能不满意;

POST http://localhost:7071/api/upload
Content-Type: application/json; multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="files"; filename="2020-04-29.png"
Content-Type: image/png

< C:\Users\enend\OneDrive\Pictures\Screenshots\2020-04-29.png
------WebKitFormBoundary7MA4YWxkTrZu0gW--

private async Task<UploadCommand?> GetCommandAsync(HttpRequestData httpRequest)
        {
            try
            {
                var command =  await httpRequest.ReadFromJsonAsync<UploadCommand>();

                if(command == null) return null;

                var parser = await MultipartFormDataParser.ParseAsync(httpRequest.Body);
                
                command.Files = parser.Files.ToList();

                return command;
            }
            catch(Exception ex)
            {
                _log.LogError(ex.ToString());
                return null;
            }
        }
    }
public class UploadCommand
    {
        [JsonPropertyName("files")]
        public IEnumerable<FilePart> Files {get;set;} = new List<FilePart>();
        [JsonPropertyName("culture")]
        public string? Culture { get; set; }
        [JsonPropertyName("status")]
        public string? Status { get; set; }
        [JsonPropertyName("accessType")]
        public string? AccessType { get; set; } 
        [JsonPropertyName("folders")]
        public IEnumerable<Folder>? Folders { get; set; }
        [JsonPropertyName("fileTypes")]
        public IEnumerable<string>? FileTypes { get; set; }
        [JsonPropertyName("allowOverrides")]
        public bool AllowOverride { get; set; }
    }

上面的代码可以工作,但我无法想办法向其中添加 json,所以我的函数接受它(我可以单独发送 json,但不能一起发送)

任何想法都会被采纳。

api rest azure-functions httpclient rest-client
1个回答
0
投票

您需要使用

multipart/form-data
在消息的根部定义您的内容类型,之后每个独特的部分将定义
content-type

POST "https://yourdomain.com/upload" HTTP/1.1
Authorization: ''
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name='image'; filename:"test_file.png"
Content-Type: image/png
Content-Length: <number>

<test_file data in bytes>

----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name='filename'
Content-Type: application/json
Content-Length: <number>

{
    "image": "<filename>",
    "countryCode": "US"
}
----WebKitFormBoundary7MA4YWxkTrZu0gW--
© www.soinside.com 2019 - 2024. All rights reserved.