2010-05-23 30 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請求發送。