2010-08-17 61 views
1

我有上傳圖像到SQL數據庫的問題。 我有方法上傳控制器上傳圖像上傳到SQL的問題

dbData userDb = new dbData();

public ActionResult Upload() 
{ 
    return View(); 
} 

[HttpPost] 
public ActionResult Upload(HttpPostedFileWrapper file) 
{ 
    if (file.ContentLength > 0) 
    { 
     Stream fileStream = file.InputStream; 
     string fileName = Path.GetFileName(file.FileName); 
     int fileLength = file.ContentLength; 
     byte[] fileData = new byte[fileLength]; 
     fileStream.Read(fileData, 0, fileLength); 

     var image = new ImageTable(); 
     image.Image = fileData; 
     image.Description = "Default profile picture"; 

     try 
     { 
      userDb.ImageTables.InsertOnSubmit(image); 
      userDb.SubmitChanges(); 
      return RedirectToAction("Success"); 
     } 
     catch (Exception ex) 
     { 
      throw; 
     } 

    } 
    return View(); 
} 

如果我用這個視圖頁面

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<html xmlns="http://www.w3.org/1999/xhtml" > 
<head runat="server"> 
    <title>Upload</title> 
</head> 
<body> 
    <div> 

    <% using (Html.BeginForm("Upload", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" })) 
     {%> 
     <input name="file" type="file" runat="server" id="file"/><br /> 
     <input type="submit" value="Upload File" /> 
<%} %> 
    </div> 
</body> 
</html> 

everithing的偉大工程,但如果我想使用視圖拼命地跑在母版後,我點擊上傳提交按鈕i西港島線得到這個錯誤:

No parameterless constructor defined for this object. 

知道某人在哪裏是問題,我該如何解決它? 謝謝

回答

1

發生此錯誤是因爲默認模型聯編程序無法創建不包含無參數構造函數的類的實例(如HttpPostedFileWrapper)。

最簡單的方法是從Request.Files(例如Request.Files["file"])中提取文件。

或者,您可以爲其創建自定義模型聯編程序。

UPDATE:

這是操作方法我使用:

[HttpPost] 
public ActionResult Index(FormCollection form) 
{ 
    var file = Request.Files["file"]; 
    if(file != null && file.ContentLength > 0) 
    { 
     // ... 
    } 

    return View(); 
} 
+0

如果我使用像..>公共的ActionResult上傳Request.Files({的FormCollection如果(Request.Files [ 「文件」]。 ContentLength> 0)... bla bla bla 我在「IF」行遇到錯誤 SystemNullReference異常>對象引用未設置爲對象的實例 – 2010-08-18 08:44:15

+0

它應該工作,您必須做其他事情我錯了。將問題編碼到視圖中,設置後期操作,選擇文件,提交併運行。 – Necros 2010-08-18 15:28:45

+0

你可以寫我使用後腳本嗎? 我加了這個代碼:foreach(在Request.Files中的字符串postedFile){ HttpPostedFileBase file = Request.Files [postedFile]; 如果(file.ContentLength> 0) 它的工作原理,但是當我使用代碼在每個foreach循環中它不起作用 – 2010-08-18 18:02:39