I'm developing a Web API with .Net Core, where I need to allow a client to upload a list of files (mostly images) and save them to the server.
The problem is that when the image is uploaded, and I try to open it from the folder where it was saved, it seems like it's corrupted and its size is not the same as the initial one.
Here is the code of my controller:
[Route("api/TestUpload")]
[Consumes("multipart/form-data")]
public class TestUploadController : Controller
{
private readonly IHostingEnvironment _env;
private readonly ApplicationContext _context;
public TestUploadController(ApplicationContext context, IHostingEnvironment env)
{
_context = context;
_env = env;
}
// GET: /<controller>/
public IActionResult Index()
{
return View();
}
[HttpPost("upload")]
public async Task<IActionResult> Post([FromForm]IList<IFormFile> files)
{
long size = files.Sum(f => f.Length);
var uploads = Path.Combine(_env.WebRootPath, "uploads");
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
var filePath = Path.Combine(uploads, formFile.FileName);
using (var fileStream = new FileStream(Path.Combine(uploads, formFile.FileName), FileMode.Create))
{
await formFile.CopyToAsync(fileStream);
fileStream.Flush();
}
}
}
return Ok(new { size });
}
}
The only files that seem to be uploaded and saved fine are text and html files. I've tried with a single file instead of a list, same thing.
I've tried several code variations and none seem to work, I'm probably doing something wrong but I just can't figure out what it is.
Here is a screenshot of a test with Advanced REST client: ARC screenshot
And here is what I mean by "it seems like it's corrupted": Windows Photo Viewer screenshot
Any help is appreciated!
sizeis to small. How are you uploading this file?formFile.CopyTo(fileStream);instead of doing it asynchronously but nothing changes.multipart/form-dataas thecontent type.Flushis unecessary and can be removed, but I don't think that's causing the issue. Are you sure the files are good to begin with?