ASP.Net 5 上传文件通过虚拟路径存储

先贴上代码

  [HttpPost]
        public IActionResult ImportTeaching(IFormFile file)
        {
            string root = @"Temp/teachingfile/";
            string phyPayh = evn.MapPath(root);
            if (file != null)
            {
                var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
                var originalName = parsedContentDisposition.FileName.Replace(""", "");
                file.SaveAs(phyPayh + originalName);
            }
            else
            {
                ModelState.AddModelError("", "没有选择文件");
                return View();
            }
            return RedirectToAction("Index");
        }

这里必须先获取服务里面的IHostingEnvironment

如下代码

  [FromServices]
        public IHostingEnvironment evn { set; get; }

注意:这个

IHostingEnvironment在启动的时候已经自动注册到服务里面了。可以直接获取

特别注意:

 现在的虚拟路径写法以前的mvc5 有所不同 以前 是类似:string root = "~/LiveFile/";

现在是 :string root = "LiveFile/";

我之前按照mvc5的写法试了很多次 都是不通过的。

原文地址:https://www.cnblogs.com/nele/p/4944913.html