simple image upload in aspnet mvc

左心房为你撑大大i 提交于 2020-01-13 19:37:48

问题


i'm building a simple school portal, i have stucked at uploading an image into my application, i.e a user should upload school image to my server, i have directory for images as ./Content/Images -- all uploading images should be uploaded to this directory. i have following code


input type="file" id="SchoolImageUrl" name="SchoolImageUrl" class="required"    

using this m'getting a browse button, i have no idea how to upload that image to server and how would be my action controller ? i have following controller for creating school


public ActionResult SchoolCreate(_ASI_School schoolToCreate, FormCollection collection)
        {
            if (!ModelState.IsValid)
                return View();
            try
            {
                // TODO: Add insert logic here
                schoolToCreate.SchoolId = Guid.NewGuid().ToString();
                schoolToCreate.UserId = new Guid(Request.Form["currentUser"]);
                schoolToCreate.SchoolAddedBy = User.Identity.Name;
                HttpPostedFileBase file = Request.Files["SchoolImageUrl"];
                file.SaveAs(file.FileName);
                //schoolToCreate.SchoolImageUrl = Reuseable.ImageUpload(Request.Files["SchoolImageUrl"], Server.MapPath("../Content"));
                //schoolToCreate.SchoolImageUrl = Path.GetFullPath(Request.Files[0].FileName);
                schoolToCreate.SchoolImageUrl = collection["SchoolImageUrl"];

                UpdateModel(schoolToCreate);
                _schoolRepository.CreateSchool(schoolToCreate);
                //_schoolRepository.SaveToDb();

                return RedirectToAction("DepartmentCreate", "Department", new { userId = schoolToCreate.UserId, schoolId = schoolToCreate.SchoolId });
            }
            catch
            {
                return View("CreationFailed");
            }
        }

here im geting object referece error


回答1:


Take a look at this post

HttpPostedFileBase file = Request.Files["SchoolImageUrl"];

may be causing it. Did you debug to check if it's getting a null value?




回答2:


Does your Html.BeginForm include this:

new { enctype = "multipart/form-data" }

Otherwise the file data won't be sent in the POST request.



来源:https://stackoverflow.com/questions/2891522/simple-image-upload-in-aspnet-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!