IFormFile上传图像ASP.NET核心MVC

很抱歉打扰你们,但我有一个问题,我不知道如何解决,我已经浏览了几天,正在尝试其他解决方案。

因此,我正在建立一个网站,我希望在该网站上实现一个用户部分,以便用户可以将其个人图像上传为图片个人资料。

这是我提出的问题所在,当我运行代码时,它总是返回null。

这是我的控制器:

callback

这是我的观点

[HttpPost]
    public async Task<IactionResult> Create(EmployeeCreateViewModel model)
    {

        if (ModelState.IsValid)
        {


            string uniqueFileName = null;
            if(model.Photo != null)
            {
                string uploadsFolder = Path.Combine(_hostingEnvironment.WebRootPath,"EmpImg");
                uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Photo.FileName;
                using(var fs = new FileStream(Path.Combine(uploadsFolder,uniqueFileName),FileMode.Create))
                {
                    await model.Photo.CopyToAsync(fs);
                }


            }
            Employee newEmployee = new Employee
            {
                Name = model.Name,Surname = model.Surname,Email = model.Email,Area = model.Area,PhotoPath = uniqueFileName
            };
            _employeeRepository.Add(newEmployee);
            return RedirectToaction("details",new { id = newEmployee.Id });
        }

        return View();

    }

当我尝试在浏览器中上传img时,它没有抛出任何异常,它只是没有将图像上传到数据库,并且列为NULL。

在此先感谢大家的帮助或建议。

qutingjian1 回答:IFormFile上传图像ASP.NET核心MVC

Create视图中,为name="Create"字段添加额外的Photo,这会导致模型绑定失败。您需要将名称与模型的字段名称匹配。>

从以下位置更改以下代码

<div class="form-group row">
    <label asp-for="Photo" class="col-sm-2 col-form-label"></label>
    <div class="col-sm-10">
        <div class="custom-file">
            <input asp-for="Photo" name="Create" class="form-control custom-file-input" />
            <label class="custom-file-label">Choose File...</label>
        </div>
    </div>
</div>

<div class="form-group row">
    <label asp-for="Photo" class="col-sm-2 col-form-label"></label>
    <div class="col-sm-10">
        <div class="custom-file">
            <input asp-for="Photo" class="form-control custom-file-input" />
            <label class="custom-file-label">Choose File...</label>
        </div>
    </div>
</div>

型号:

public class EmployeeCreateViewModel
{

    public string Name { get; set; }
    public string Surname { get; set; }
    public string Email { get; set; }
    public string Area { get; set; }
    public IFormFile Photo { get; set; }
}
本文链接:https://www.f2er.com/3156911.html

大家都在问