在 C# 控制台应用程序中使用 HttpClient 上传文件

Upload file with HttpClient in C# Console Application

我需要帮助。

我正在尝试在控制台应用程序中上传文件,但无法正常工作。

我需要以这种格式发送:

    {
        "name": "arquivoIndex",
        "request": {
            "auth": {
                "type": "bearer",
                "bearer": {
                    "token": "{{usrToken}}"
                }
            },
            "method": "POST",
            "header": [],
            "body": {
                "mode": "formdata",
                "formdata": [
                    {
                        "key": "arquivos",
                        "type": "file",
                        "src": "filepath"
                    }
                ]
            },
            "url": ""
        },
        "response": []

我正在构建这段代码:

        HttpClientHandler _manipulador = new HttpClientHandler();
        HttpClient _cliente = new HttpClient(_manipulador);

        _cliente.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue(
                "Bearer", tokenAplicacao_);

但是 body,我已经尝试了一些代码,但没有任何效果

这应该有效,或者至少给你一个试验的基础:

        using HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", YOUR_TOKEN);
        var fileContents = new ByteArrayContent(File.ReadAllBytes(PATH_TO_FILE_TO_UPLOAD));

        fileContents.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");

        using var form = new MultipartFormDataContent();
        form.Add(fileContents, "file", Path.GetFileName(PATH_TO_FILE_TO_UPLOAD));

        var response = await client.PostAsync("https://yoursite.com/upload", form);
        var result = await response.Content.ReadAsStringAsync();