aspnet mvc中的简单图像上传

时间:2010-05-23 11:31:19

标签: asp.net-mvc file-upload upload

我正在建立一个简单的学校门户网站,我一直坚持将图像上传到我的应用程序,即用户应该将学校图像上传到我的服务器,我有图像目录为./Content/Images - 所有上传图像应该上传到这个目录。我有以下代码


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

使用这个m'getting浏览按钮,我不知道如何将该图像上传到服务器,我的动作控制器怎么样?我有以下控制器来创建学校


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");
            }
        }

此处提示对象参考错误

2 个答案:

答案 0 :(得分:3)

你的Html.BeginForm是否包含这个:

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

否则,文件数据将不会在POST请求中发送。

答案 1 :(得分:1)

查看this post

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

可能会导致它。您是否进行了调试以检查它是否获得空值?