.net API Upload File

//Declare a simple class with IFormFile (require a package Microsoft.AspNetCore.Http.Features) public class FileInputDto { public IFormFile FileToUpload { get; set; } } // On Controller [HttpPost, DisableRequestSizeLimit, Route("Update")] public IActionResult Upload([FromForm] FileInputDto file) { try { var folderName = "tmp"; var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName); if (file.FileToUpload.Length > 0) { var fileName = ContentDispositionHeaderValue.Parse(file.FileToUpload.ContentDisposition).FileName.Trim('"'); var fullPath = Path.Combine(pathToSave, fileName); var dbPath = Path.Combine(folderName, fileName); using (var stream = new FileStream(fullPath, FileMode.Create)) { file.FileToUpload.CopyTo(stream); } return Ok(true); } else { return BadRequest(); } } catch (Exception ex) { return StatusCode(500, $"Internal server error: {ex}"); } } // Call It from anywhere curl -X POST \ <yourroute>/Update \ -F file.FileToUpload=@test.zip
Works with .net 5
"tmp" directory have to exist

Remarks in postman :
Body > Form Data
Add a field : File.FileToUpload (type file)
Add your file as value

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.