I implemented in my API a Controller to upload files with an HTTP Post
request, nothing challenging from what you find on the web:
public async Task<IActionResult> Post()
{
if (string.IsNullOrEmpty(Request.GetMultipartBoundary()))
{
return StatusCode(415);
}
long size = Request.Form.Files.Sum(f => f.Length);
var filePath =
Path.Combine(_hostingEnvironment.ContentRootPath, "TempUploads");
string fileName = "";
List<string> tempFileName = new List<string>();
foreach (var formFile in Request.Form.Files)
{
fileName = formFile.FileName;
string timeStamp = DateTime.Now.ToString("yyyyMMddHHmmssfff");
fileName = fileName.Replace(Path.GetExtension(formFile.FileName),
timeStamp + Path.GetExtension(formFile.FileName));
filePath = filePath + "\\" + fileName;
if (formFile.Length > 0)
{
using(var stream = new FileStream(filePath, FileMode.Create))
{
await formFile.CopyToAsync(stream);
}
}
tempFileName.Add(fileName);
}
return Ok(new { tempFileName });
}
It adds a timeStamp
to the name, but I already tried without it and it doesn't change anything.
The problem I get is that if I upload files bigger than around 4KB
(still really small) they either are corrupted (won't open) or are empty (same amount of pages, but all blank) and weight a couple KB more.