Home > Back-end >  How to send and receive multipart/form-data containing files in .NET Core?
How to send and receive multipart/form-data containing files in .NET Core?

Time:11-02

Using .NET Core 3.1, I have the following Http client which builds a HTTP POST containing multipart/form-data body:

public async Task SendRequest(string randomString, IFormFileCollection files) 
{
    var form = new MultipartFormDataContent();
    
    form.Add(new StringContent(randomString), "randomString");
    
    foreach (var file in files)
    {
        var stream = new MemoryStream();
        await file.CopyToAsync(stream, cancellationToken);
        form.Add(new StreamContent(stream), "files");
    }

    using var request = new HttpRequestMessage(HttpMethod.Post, $"api/endpoint")
    {
        Content = form
    };

    await _httpClient.SendAsync(request);
}

The receiving controller looks like this:

[Consumes("multipart/form-data")]
[HttpPost]
public async Task ReceiveForm([FromForm] RequestModel request)
{
    //Do stuff
}

RequestModel looks like this:

public class RequestModel 
{
    [JsonPropertyName("randomString")]
    public string RandomString { get; set; }

    [JsonPropertyName("files")]
    public IFormFileCollection Files { get; set; }
}

The problem I am seeing is that requestModel.RandomString gets populated, but the requestModel.Files does not - it is null. What am I doing wrong?

CodePudding user response:

thanks for the perfect code in example!

You should set both parameters (name and fileName) to files - form.Add(new StreamContent(stream), "files", "files");

Method description:

Parameters:
content: The HTTP content to add to the collection.
name: The name for the HTTP content to add.
fileName: The file name for the HTTP content to add to the collection.

This is my example:

var fileName = "files";
var byteArrayContent = new ByteArrayContent(fileBytes1);
form.Add(byteArrayContent, fileName, fileName);

var stream = new MemoryStream(fileBytes2);
form.Add(new StreamContent(stream), fileName, fileName);

Results: Results

  • Related