实际上,我正在尝试从用户上传文件。但是我出错了。我也尝试过各种方法,甚至Microsoft doc也是如此。我无能为力所以请帮助我
链接:Microsoft Doc dotnet core 3.1
我的动作:
[HttpPost]
public async Task<IActionResult> Updateperson(UpdatePersonViewModel updatePerson)
{
if (ModelState.IsValid)
{
string uniqueFileName = null;
if(updatePerson.Photo != null)
{
string[] words = updatePerson.Photo.FileName.Split('.');
int a = words.Rank;
uniqueFileName = words[a];
uniqueFileName = Guid.NewGuid().ToString() + "_." + uniqueFileName;
string filePath = Path.Combine("Images",uniqueFileName);
//string filePath = Path.Combine(config["Images"], uniqueFileName);
// using (var stream = System.IO.File.Create(filePath))
// {
// await formFile.CopyToAsync(stream);
// }
await updatePerson.Photo.CopyToAsync(new FileStream(filePath,FileMode.Create));
}
_context.Persons.Update(updatePerson);
_context.SaveChanges();
return RedirectToAction("Profile", new RouteValueDictionary(new { action = "Profile", id = updatePerson.Id }));
}
else
{
return RedirectToAction("Profile", new RouteValueDictionary(new { action = "Profile", id = updatePerson.Id }));
}
}
>>> config是IConfiguration的对象
这意味着不存在名为Image的目录!
您可以简单地检查它是否存在,如果不存在,则可以创建一个。
if(!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
要测试:
使用这样的directoryPath
变量:
var directoryPath=Path.Combine(Directory.GetCurrentDirectory(), "Images");