Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File upload to wwwroot folder in ASP.NET Core

Why is my following codes sometimes work, but sometimes it does't work?

 private bool UploadFile(IFormFile ufile, string fname)
 {
     if (ufile.Length > 0)
     {
          string fullpath = Path.Combine(_env.WebRootPath, fname);
          using (var fileStream = new FileStream(fullpath, FileMode.Create))
          {
               ufile.CopyToAsync(fileStream);
          }
          return true;
     }
     return false;
 }

The code did managed to save the picture to a folder which I created under wwwroot, but the picture is not appearing, and even in Visual Studio too.

Is there a way to solve it?

Thanks.

Even when I open up the file explorer of the folder that is storing the pictures, the picture is like is there but not showing any image.

like image 720
Matt Avatar asked Jan 16 '19 04:01

Matt


1 Answers

Try as follows. File will be uploaded to images folder under wwwroot folder.

private async Task<bool> UploadFile(IFormFile ufile)
{
     if (ufile != null && ufile.Length > 0)
     {
          var fileName = Path.GetFileName(ufile.FileName);
          var filePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images", fileName);
          using (var fileStream = new FileStream(filePath, FileMode.Create))
          {
              await ufile.CopyToAsync(fileStream);
          }
          return true;
      }
      return false;
}
like image 141
TanvirArjel Avatar answered Oct 25 '22 15:10

TanvirArjel