File upload to wwwroot folder in ASP.NET Core

Viewed 20714

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.

3 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;
}

Had same problem with dot net core, here's what I did:

-Make virtual directory

-Map it to that folder path (inside wwwroot)

-Make your fullpath equals to this VD ; absolute path (can keep it in config file)

-Give write permissions for this folder to iisuser

allow accessing to static files, just add this line in you startup.cs file under Configure method:

app.UseStaticFiles();
Related