簡體   English   中英

誰能告訴我如何將物理文件保存到配置提供的路徑 - ASP.NET Core MVC

[英]Can Anyone Show Me How to Save Physical Files to a Path Provided by Configuration - ASP.NET Core MVC

我是 ASP.NET Core 開發的新手。 我正在嘗試設置一個允許特定用戶將文件上傳到我的網絡服務器的應用程序。 我已成功將文件上傳到臨時目錄,但想將文件保存在“wwwroot/images”而不是臨時目錄中。

以下是處理文件上傳的控制器列表:

        [HttpPost("FileUpload")]
        [DisableFormValueModelBinding]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Index(List<IFormFile> files)
        {

            long size = files.Sum(f => f.Length);

            var filePaths = new List<string>();
            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    /*full path to file in temp location*/
                    var filePath = Path.GetTempFileName();
                    filePaths.Add(filePath);


                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await formFile.CopyToAsync(stream);

                    }
                }
            }

            /*
             * Process uploaded files. Don't rely on or trust the FileName
             * property without validation.
             */
            return Ok(new { count = files.Count, size, filePaths });

        }

如您所見,控制器將上傳的文件存儲到臨時目錄。 誰能告訴我如何手動指定存儲文件的位置?

Startup.cs 包含以下代碼:

/*To list physical files from a path provided by configuration:*/
                var physicalProvider = new PhysicalFileProvider(Configuration.GetValue<string>("StoredFilesPath"));
                services.AddSingleton<IFileProvider>(physicalProvider);

我相信這兩行允許我指定我希望上傳的文件保存到哪個目錄,作為我的 appsettings.json 文件中的字符串:

/wwwroot/images

如上所述,我對 ASP.NET Core Web 開發還是很陌生。 因此,如果我忽略了包含任何相關信息,請讓我知道我的帖子中缺少什么,我會盡力更新我的列表。 如果有人能就如何實現此功能向我提供一些指導,我將不勝感激。

感謝您的幫助。

在這種情況下,您不需要PhysicalFileProvider 您可以輕松注入IWebHostEnvironment (在以前的 asp.net 核心版本中是IHostingEnvironment ,現在已棄用)。

public string _rootPath;
public HomeController(IHostingEnvironment env)
{
    _rootPath = env.WebRootPath;
}

然后在您的 Index 操作方法中只需替換此行:

var filePath = Path.GetTempFileName();

有了這個:

var filePath = Path.Combine(_rootPath, formFile.FileName);

在 Path.Combine 中,如果您想存儲在 wwwroot 中的某處,並動態執行此操作,則在 _webRootPath 和 fileName 之間添加另一個參數,格式為files\\\\images\\thumbnailsfiles/images/thumbnails 這會將數據存儲在您的wwwroot/files/images/thumbnails

此示例特定於wwwroot如果您想存儲到外部的另一個目錄,然后更改行_rootPath = env.WebRootPath; _rootPath = env.ContentRootPath;

IHostingEnvironmentwebRoot ,它給出了 wwwroot 的路徑。 用 webRoot 附加文件名以獲取文件路徑。

string folder = env.webRoot;
string fileName = ContentDispositionHeaderValue.Parse(formFile.ContentDisposition).FileName.Trim('"');
string fullPath = Path.Combine(folder, fileName);

注意: env作為參數注入到構造函數中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM