英文:
why i can not find WebRootPath in .netcore
问题
以下是您的代码的中文翻译部分:
这是我的代码
当我尝试在POST方法中使用它时,它不起作用并显示错误
private readonly IWebHostEnvironment Environment;
public uploadController(IWebHostEnvironment _environment)
{
Environment = _environment;
}
[HttpPost]
public IActionResult Upload(IFormFile file)
{
if (file != null)
{
var uniqueFileName = GetUniqueFileName(file.FileName);
var uploads = Path.Combine(Environment.WebRootPath, "Uploads");
var filePath = Path.Combine(uploads, uniqueFileName);
file.CopyTo(new FileStream(filePath, FileMode.Create));
}
return Redirect("https://google.com");
}
private string GetUniqueFileName(string fileName)
{
fileName = Path.GetFileName(fileName);
return Path.GetFileNameWithoutExtension(fileName)
+ "_"
+ Guid.NewGuid().ToString().Substring(0, 4)
+ Path.GetExtension(fileName);
}
请注意,我已将代码中的HTML实体代码 "
替换为双引号(")以保持代码的可读性。
英文:
this is my code
when i trying use it in method post it dont work and show me error
private readonly IWebHostEnvironment Environment;
public uploadController(IWebHostEnvironment _environment)
{
Environment = _environment;
}
[HttpPost]
public IActionResult Upload(IFormFile file)
{
if (file!= null)
{
var uniqueFileName = GetUniqueFileName(file.FileName);
var uploads = Path.Combine(Environment.WebRootPath, "Uploads");
var filePath = Path.Combine(uploads, uniqueFileName);
file.CopyTo(new FileStream(filePath, FileMode.Create));
}
return Redirect("https://google.com");
}
private string GetUniqueFileName(string fileName)
{
fileName = Path.GetFileName(fileName);
return Path.GetFileNameWithoutExtension(fileName)
+ "_"
+ Guid.NewGuid().ToString().Substring(0, 4)
+ Path.GetExtension(fileName);
}
}
答案1
得分: 0
Environment.WebRootPath 如果位于项目的根目录下的 wwwroot 文件夹被意外移除,也可能为 null。
尝试将一个 wwwroot 文件夹添加到项目的根目录下。
结果:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论