CRUD Functions for creating folder in wwwroot

371 Views Asked by At

I want to create a function which can create folder inside wwwroot folder. Because my client requirement is to create albums (folder). I need to save this albums in my root folder and then the pictures in those folders. For example : BirthdayAlbum, WeedingAlbum and so on..

How can i do this in ASP.NET Core MVC?

1

There are 1 best solutions below

0
On

Although your question does not include what you have done so far but I hope this will help you in a way:

public async Task<IActionResult> Upload(string folder)
      {
           if (folder == null)
           {
                folder = "Uploads";
           }

           var file = Request.Form.Files[0];
           var directory = Path.Combine(_environment.WebRootPath, $"{folder}");
           var filePath = $"{Request.Scheme}://{Request.Host}/{folder}/";
           var finalFileName = "";
           if (file.Length > 0)
           {
                if (!Directory.Exists(directory))
                {
                     Directory.CreateDirectory(directory);
                }
                var fileName = Path.GetFileName(Guid.NewGuid().ToString().Substring(0, 12).ToLower() + file.FileName);
                var path = Path.GetFullPath(directory);
                using (var fileStream = new FileStream(Path.Combine(path, fileName), FileMode.Create, FileAccess.ReadWrite))
                {
                     await file.CopyToAsync(fileStream);
                }
                finalFileName = fileName;
           }

           return Ok($"{filePath + finalFileName}");
      }

NOTE: Please inject IWebHostEnvironment in your controller constructor if you are using ASP.NET Core 3.1 or its equivalent if lower.

What the above code does is to allow you create folders in the wwwroot folder with the folder name you specified and as well upload images or files.

I hope this helps you resolve the issue.