2

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

George Stocker
  • 57,289
  • 29
  • 176
  • 237
FosterZ
  • 3,863
  • 6
  • 38
  • 62
  • Try [this practical example](http://stackoverflow.com/questions/1653469/how-can-i-upload-a-file-and-save-it-to-a-stream-for-further-preview-using-c/1653508#1653508) for simple uploading in MVC but also [consider this point](http://stackoverflow.com/questions/851318/asp-net-mvc-1-to-many-saving-post-and-upload-files/851326#851326) about "attaching" the files later. – Matt Kocaj May 24 '10 at 05:50

2 Answers2

4

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
  • 14,268
  • 17
  • 76
  • 108
2

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ı
  • 37,978
  • 12
  • 114
  • 156