在ASP.net核心中上传图片保持NULL

时间:2019-05-13 09:49:11

标签: c# asp.net

我正在尝试将文件路径传递到我的ProfileViewModel中,但即使其他值都已填充,它似乎也保持Null。

我尝试调试它,但似乎找不到错误的地方。

我的观点

@using (Html.BeginForm("EditProfile", "Profile", FormMethod.Post))
{
    @Html.AntiForgeryToken()

        @Html.LabelFor(model => model.Photo, htmlAttributes: new { @class = "control-label col-md-2" })
        <input asp-for="Photo" type="file"/><br />

        <div class="form-group"> 
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>

我的控制器

        public IActionResult profile()
        {
            return View();
        }

        private readonly IHostingEnvironment he;
        public ProfileController(IHostingEnvironment e)
        {
            he = e;
        }

        [HttpPost]
        public ActionResult EditProfile(ProfileViewModel profile)
        {
            string ID = Request.Cookies["UserID"];
            if (ModelState.IsValid)
            {
                var Photo = profile.Photo;
                var FileName = Path.Combine(he.WebRootPath, Path.GetFileName(Photo.FileName));
                if (logicprofile.logicEditProfile(profile.BIO, profile.Sex, profile.Preffered, FileName, Convert.ToInt32(ID)) == true)
                {
                    profile.Photo.CopyTo(new FileStream(FileName, FileMode.Create));
                    ViewBag.Message = "Profile Updated";
                    return View("profile", profile);
                }
                else
                {
                    ViewBag.Message = "Something went wrong";
                    return View("profile", profile);
                }
            }
            else
            {
                return View("profile", profile);
            }


        }

ViewModel

[DisplayName("A picture of you!")]
public IFormFile Photo { get; set; }

我希望我的图片保存在文件夹和数据库路径中,以便将它们用作个人资料图片。

2 个答案:

答案 0 :(得分:0)

您应该在表单中使用enctype来传递文件类型数据。

toMap()

答案 1 :(得分:0)

您需要在视图中添加multipart / form-data之类的

<form id="form1" method="post" asp-controller="Demo" asp-action="Register" enctype="multipart/form-data">

并确保您的照片模型是这样的

public IFormFile Photo { get; set; }
相关问题