2013-05-12 51 views
0

我遇到了文件上傳問題。 這裏是我的控制器文件上傳問題MVC 4

public class StoreManagerController : Controller 
    { 
    private StoreContext db = new StoreContext(); 

    //Some actions here 

    // 
    // POST: /StoreManager/Create 

    [HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Create(Book book, HttpPostedFileBase file) 
    { 
     if (ModelState.IsValid) 
     { 
      book.CoverUrl = UploadCover(file, book.BookId); 
      db.Books.Add(book); 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 

     ViewBag.AuthorId = new SelectList(db.Authors, "AuthorId", "Name", book.AuthorId); 
     ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", book.GenreId); 
     ViewBag.PublisherId = new SelectList(db.Publishers, "PublisherId", "Name", book.PublisherId); 
     return View(book); 
    } 

    private string UploadCover(HttpPostedFileBase file, int id) 
    { 
     string path = "/Content/Images/placeholder.gif"; 
     if (file != null && file.ContentLength > 0) 
     { 

      var fileExt = Path.GetExtension(file.FileName); 
      if (fileExt == "png" || fileExt == "jpg" || fileExt == "bmp") 
      { 
       var img = Image.FromStream(file.InputStream) as Bitmap; 
       path = Server.MapPath("~/App_Data/Covers/") + id + ".jpg"; 
       img.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg); 
      } 
     } 

     return path; 
    } 
} 

我創建視圖

@using (Html.BeginForm("Create", "StoreManager", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
@Html.AntiForgeryToken() 
@Html.ValidationSummary(true) 
    @/* divs here */@ 
    <div class="editor-label"> 
     Cover 
    </div> 

    <div class="editor-field"> 
     <input type="file" name="file" id="file"/> 
    </div> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.Description) 
    </div> 

    <p> 
     <input type="submit" value="Create" /> 
    </p> 
</fieldset> 

}

當我嘗試上傳文件時,我得到了一個默認的佔位符。所以我認爲帖子數據爲空。 但是,當我用瀏覽器檢查它給我的下一個職位數據

------WebKitFormBoundary5PAA6N36PHLIxPJf 
Content-Disposition: form-data; name="file"; filename="1.JPG" 
Content-Type: image/jpeg 

我在做什麼錯?

+5

請減少問題中的代碼,使它只包含相關的代碼 – 2013-05-12 12:50:17

回答

1

我可以看到,這是錯誤的第一件事情是這樣的條件:

if (fileExt == "png" || fileExt == "jpg" || fileExt == "bmp") 

這將永遠不會返回true,因爲Path.GetExtension包括「」在文件擴展名中。這聽起來像這可能是你的主要問題,因爲這將簡單地跳過條件塊,你將留下你的佔位符。這將需要更改爲:

if (fileExt == ".png" || fileExt == ".jpg" || fileExt == ".bmp") 

但是,您的問題中有太多的代碼,因此很難確定這是否是唯一的問題。

如果你還有問題,我建議把一個斷點在你的控制器動作(你沒有指定這是否是EditCreate並檢查是否file值符合預期。您應該能夠隔離哪裏問題出在那裏 - 如果仍然無法解決 - 至少可以縮小你的問題的範圍。

+0

非常感謝你,問題在於這個條件,還有一個問題,你可以給我一個關於asp.net mvc代碼調試的鏈接,我不能調整它的調試方式 – 2013-05-13 12:36:58

+0

這很簡單,如果你運行你的應用程序n調試模式(通常爲F5),您可以簡單地在應用程序中放置斷點,並在運行時檢查變量和對象屬性的值。在這裏閱讀更多信息:http://www.codeproject.com/Articles/79508/Mastering-Debugging-in-Visual-Studio-2010-A-Beginn – 2013-05-13 15:12:01