2010-05-23 94 views
1

我正在建设一个简单的学校门户网站,我stucked上传图像到我的应用程序,即用户应该上传学校图像到我的服务器,我有图像目录为./Content/图片 - 所有上传的图片都应该上传到这个目录。我有以下代码简单的图像上传在aspnet mvc

 

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

这里IM葛亭对象referece错误

+0

尝试[此实际示例](http://stackoverflow.com/questions/1653469/how-can-i-upload-a-file-and-save-it-to-a-stream-for-further-预览使用C/1653508#1653508)简单上传在MVC,但也[考虑这一点](http://stackoverflow.com/questions/851318/asp-net-mvc-1-to-many-saving-post -and-upload-files/851326#851326)关于稍后“附加”文件。 – 2010-05-24 05:50:54

回答

1

this post

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

看一看可能导致它。你调试过,检查它是否得到一个空值?

3

贵Html.BeginForm包括此:

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

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