Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC ASP.NET CORE, Uploading files sometime the file being uploaded become corrupted / size 0 byte

So I am trying to upload files in my mvc core and it works, however, sometime the file being uploaded is like corrupted or size 0 bytes. Does anyone ever experienced something like this? The initial file size being uploaded is not large at all.

Thanks.

public IActionResult UploadCertificateFile(IFormFile UploadCertificate)
        {
            var parsedContentDisposition =
                   ContentDispositionHeaderValue.Parse(UploadCertificate.ContentDisposition);
            var filename = Path.Combine(_hostingEnvironment.WebRootPath,
                "Uploads", parsedContentDisposition.FileName.Trim('"'));
            using (var stream = System.IO.File.OpenWrite(filename))
            {
                UploadCertificate.CopyToAsync(stream);
            }
            return RedirectToAction("Index");
        }
like image 985
Sarah Avatar asked Nov 27 '25 01:11

Sarah


1 Answers

I think the problem here is using CopyToAsync and not calling await, I think you should make your method declaration async Task and call await in UploadCertificate.CopyToAsync line, or just use CopyTo (but is better for I/O to make it async)

File might not be copied fully, when you thread is killed, so this is why your file is corrupted.

like image 184
kriss Avatar answered Nov 30 '25 00:11

kriss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!