Upload File in API. (with Body From-Data) in the Dotnet core, WPF Windows Application (Also Can in Web Controller). and Successfully upload Files.
Model Class
public class TestDocumentModel
{
public int Id { get; set; }
public string Name { get; set; }
public IFormFile formFiles { get; set; }
}
API Controller
public async Task<IActionResult> UploadModelFiles([FromForm]TestDocumentModel models)
{
var filePath = Path.Combine(@"Custome File Save Path");
if (models.formFiles != null)
{
long sizeOfFile = models.formFiles.Length;
if (filePath.Length > 0)
{
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
if (Directory.Exists(filePath))
{
using (var fileStream = new FileStream(Path.Combine(filePath, models.formFiles.FileName), FileMode.Create))
{
await models.formFiles.CopyToAsync(fileStream);
}
}
}
}
return Ok(new { sizeOfFile, filePath });
}
else
{
long fileSize = 0;
filePath = "File note Found";
return Ok(new { fileSize, filePath });
}
}
Web Controller or WPF Windows Application Class
obj = new TestModelClass();
if (dlg != null)
{
using (var httpClient = new HttpClient())
{
string fileName = dlg.SafeFileName;
using (var content = new MultipartFormDataContent())
{
obj.Id = int.Parse(tb_id.Text);
obj.Name = tb_name.Text;
FileStream fileStream = File.OpenRead(dlg.FileName);
HttpContent fileStreamContent = new StreamContent(fileStream);
content.Add(new StringContent(Convert.ToString(obj.Id)), "Id");
content.Add(new StringContent(Convert.ToString(obj.Name)), "Name");
fileStreamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "formFiles", FileName = fileName };
fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
content.Add(fileStreamContent);
using (var response = await httpClient.PostAsync("https://localhost:44359/weatherforecast/UploadModelFiles", content))
{
string apiResponse = await response.Content.ReadAsStringAsync();
}
}
}
}
File post in API Form Postman (And Successfully upload)
File post in API Form Web/WPF Windows App (But File is Corrupted or damaged.)