tags:

views:

56

answers:

3

hi,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  A: 

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?

Ufuk Hacıoğulları
A: 

Does your Html.BeginForm include this:

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

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

Jason Miesionczek
A: 

Try this practical example for simple uploading in MVC but also consider this point about "attaching" the files later.

cottsak