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;
}
CodePudding user response:
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;
}
}