kubi
kubi

Reputation: 947

How to receive a file in ASP.NET Core controller

I want to send an image with C# HttpClient, receive it in ASP.NET Core controller and save it to disk. I tried various methods but all i'm getting in controller is null reference.

My http client:

public class HttpClientAdapter
{
    private readonly HttpClient _client;

    public HttpClientAdapter()
    {
        _client = new HttpClient();
    }

    public async Task<HttpResponse> PostFileAsync(string url, string filePath)
    {
        var requestContent = ConstructRequestContent(filePath);
        var response = await _client.PostAsync(url, requestContent);
        var responseBody = await response.Content.ReadAsStringAsync();

        return new HttpResponse
        {
            StatusCode = response.StatusCode,
            Body = JsonConvert.DeserializeObject<JObject>(responseBody)
        };
    }

    private MultipartFormDataContent ConstructRequestContent(string filePath)
    {
        var content = new MultipartFormDataContent();
        var fileStream = File.OpenRead(filePath);
        var streamContent = new StreamContent(fileStream);
        var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
        imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
        content.Add(imageContent, "image", Path.GetFileName(filePath));
        return content;
    }
}

and controller:

[Route("api/files")]
public class FilesController: Controller
{
    private readonly ILogger<FilesController> _logger;

    public FilesController(ILogger<FilesController> logger)
    {
        _logger = logger;
    }

    [HttpPost]
    public IActionResult Post(IFormFile file)
    {

        _logger.LogInformation(file.ToString());
        return Ok();
    }
}

As i mentioned above, the IFormFile object i'm getting in the controller is null reference. I tried adding [FromBody], [FromForm], tried creating class with two properties: one of type string and one with type IFormFile, but nothing works. Also instead of sending file with C# HttpClient i used Postman - same thing happens.

Does anyone know solution for this problem? Thanks in advance.

Upvotes: 3

Views: 5096

Answers (1)

huysentruitw
huysentruitw

Reputation: 28101

The name of the form field must match the property name:

content.Add(imageContent, "file", Path.GetFileName(filePath));

file instead of image, since you use file in

public IActionResult Post(IFormFile file)
{
}

Upvotes: 4

Related Questions