Home > OS >  Upload file with HttpClient in C# Console Application
Upload file with HttpClient in C# Console Application

Time:09-25

I need help.

I am trying upload file, in Console Application, but it is not working.

I need send with this format:

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

I am build this code:

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

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

But the body, i already tried some code, but nothing work

CodePudding user response:

This should work, or at least give you a base to experiment with:

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