5

I've got a Web API method which accepts a list of IFormFile variables within a small class structure, to upload the files to a storage account.

public class FileInputModel
{
        public int ScenarioId { get; set; }
        public IList<IFormFile> UploadFiles { get; set; }
}


[HttpPost("UploadFiles")]
public async Task<IActionResult> UploadForm([FromForm] FileInputModel files)
{
    //UploadLogic
}

This works perfectly for a https post using Postman, but i can't quite seem to figure out how to do this using a C# programme i'm writing to link directly to this api. So far I've got some code to convert a FileStreamResult variable into an IformFile to then send in a post request, but i can't figure out how to get a FileStreamResult from a file on my pc. Here's the method i have so far.

var json = JsonSerializer.Serialize(FileInputModel);
StringContent data = new StringContent(json, Encoding.UTF8, "application/json");

try
{
    using HttpClient client = new HttpClient();

    HttpResponseMessage response = await client.PostAsync(url, data);

    return response;
}
3
  • Remove the [FromForm] binding Commented Nov 8, 2021 at 18:06
  • My problem isn't the receiving end, rather how to send the data in any correct form, so that [FromForm] wouldn't change anything since that function works fine as it is currently Commented Nov 10, 2021 at 11:56
  • Ah so depending on which front-end framework you use to make the call, make sure to add a header of Content-type: multipart/form-data; Commented Nov 10, 2021 at 15:09

1 Answer 1

6

I was getting too caught up on the IFormFile aspect of the backend, when in reality the function was just opening the stream to then use in further functions. With this I solved it by simply using a filestream in the frontend connecting c# programme and sending the information as a MultipartFormDataContent type.

using (var client = new HttpClient())
    {
        using (var content = new MultipartFormDataContent())
        {
            var fileName = Path.GetFileName(filePath);
            var fileStream = System.IO.File.Open(filePath, FileMode.Open);
            content.Add(new StreamContent(fileStream), "file", fileName);  

            var requestUri = baseURL;
            var request = new HttpRequestMessage(HttpMethod.Post, requestUri) { Content = content };
            var result = await client.SendAsync(request);

            return;
        }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Can you post the API Method sample code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.