[Solved] Image corruption when uploading files in .net core.

I had a real ‘Doh!’ moment today. I was having issues uploading images to an endpoint… after scratching my head and repeating the issue a few times, it came down to this line:

file.CopyToAsync(stream);

Notice that the CopyToAsync is asyncronous, so it will not block the code. because I was not awaiting it, it runs to the end of the method before the file can be written properly. (In my case, sometimes the files were writing ok, other times not.)

I fixed it with:

await file.CopyToAsync(stream);

Here is the rest of the code for completeness 😊

 [HttpPost("UploadFile"), DisableRequestSizeLimit]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]

public async Task<ActionResult<Image>> UploadFile(IFormFile file)
{
try
{
var folderName = Path.Combine("resources", "images");
var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);

if (!System.IO.Directory.Exists(pathToSave))
{
System.IO.Directory.CreateDirectory(pathToSave);
}

if (file != null)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
var fullPath = Path.Combine(pathToSave, fileName);
var dbPath = Path.Combine(folderName, fileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
//This was causing the file to not be properly uplaoded. It woudl only partially upload.
//file.CopyToAsync(stream);

//This fixed it
await file.CopyToAsync(stream);
}
Image i = new Image();
i.Path = fileName;

return CreatedAtAction("GetImage", new { id = i.Id }, i);
}
else
{
return BadRequest();
}
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex}");
}
}

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *