简体   繁体   English

用于在 wwwroot 中创建文件夹的 CRUD 函数

[英]CRUD Functions for creating folder in wwwroot

I want to create a function which can create folder inside wwwroot folder.我想创建一个 function,它可以在 wwwroot 文件夹中创建文件夹。 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..例如:BirthdayAlbum、WeedingAlbum 等..

How can i do this in ASP.NET Core MVC?我如何在 ASP.NET Core MVC 中执行此操作?

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.注意:如果您使用的是 ASP.NET Core 3.1 或同等版本(如果更低),请在您的 controller 构造函数中注入 IWebHostEnvironment。

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.上面代码的作用是允许您使用指定的文件夹名称在 wwwroot 文件夹中创建文件夹,并上传图像或文件。

I hope this helps you resolve the issue.我希望这可以帮助您解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM