如何在ASP.NET MVC Core中重命名IFormfile类型的文件?

时间:2018-07-11 07:36:10

标签: mongodb asp.net-core asp.net-core-mvc

这是我的代码

string filePath = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");    
    foreach (var file in files)
    {
        if (file.Length > 0)
        {
            string fileName = file.FileName.Split("\\").LastOrDefault();
            filePath = Path.Combine(filePath, fileName);
            using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
            {
                await file.CopyToAsync(fileStream);
            }
        }

我要在数据库中保存具有唯一ID(GUID)的文件名吗?

1 个答案:

答案 0 :(得分:0)

string filePath = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");    
            foreach (var file in files)
            {
                if (file.Length > 0)
                {
                    string fileName = file.FileName.Split("\\").LastOrDefault();                        
                    System.IO.File.Move(filePath+ "\\" + fileName, Convert.ToString(Guid.NewGuid())+ Path.GetExtension(fileName));
                    filePath = Path.Combine(filePath, documents.SavedAs);
                    using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
                    {
                        await file.CopyToAsync(fileStream);
                    }
                }