2016-10-05 145 views
0

我的應用程序允許用戶通過選擇圖像上傳單個圖像:@Html.TextBoxFor(m => m.Image, new {type = "file"})。如果有任何驗證錯誤,我將丟失其選定的文件。因此,我通過If(!ModelState.IsValid)代碼塊需要臨時保存:傳回HttpPostedFileBase從視圖→控制器→返回查看

public ActionResult Create(MyModel model) { 
    if (!ModelState.IsValid) 
    { 
     if(model.Image != null && model.Image.ContentLength > 0) { 
     var displayName = Path.GetFileName(model.Image.FileName); 
     var fileExtension = Path.GetExtension(displayName); 
     var fileName = string.Format("{0}{1}", Guid.NewGuid(), fileExtension); 
     var path = Path.Combine(Server.MapPath("~/App_Data/Files"), fileName); 
     model.Image.SaveAs(path); 
     model.displayName = displayName; 
     model.FilePath = path; 
     return View(model); 
    } 
} 

我在視圖中使用@Html.HiddenFor(m => m.FilePath)

model.Image類型是HttpPostedFileBase。我必須以某種方式重新獲得用戶選擇圖像HttpPostedFileBase!ModelState.IsValid,以便能夠將其保存在數據庫中。任何機會傳回@Html.TextBoxFor(m => m.Image, new {type = "file"})內的信息?

How I later convert HttpPostedFileBase to byte[], in order to store image-data in database.

我不知道怎麼跟我有工具做到這一點。

編輯:模型屬性:

public string displayName { get; set; } 
public string FilePath { get; set; } 
public HttpPostedFileBase Image { get; set; } 
+1

不,你不能考績一個屬性public byte[] Image { get; set; }(M => m.Image,新{TYPE =「文件」})'出於安全原因。 (參考[MVC文件上傳保存選定的文件](http://stackoverflow.com/questions/29261726/mvc-file-upload-save-selected-file))。你已經有一個隱藏的輸入文件路徑,所以如果'ModelSta te'現在在重新提交後有效,然後根據隱藏輸入的值獲取已保存的文件,並將其轉換爲字節數組,如果您想將其保存在數據庫 –

+1

使用'byte [] bytes = System.IO.File.ReadAllBytes(model.FilePath);' –

回答

1

你不能爲安全起見文件輸入的值(它只能由用戶選擇在瀏覽器中的文件中設置)。

在視圖中,您將需要一個條件檢查顯示文件名和路徑(最初這將是null

@if (Model.displayName != null) 
{ 
    <div>@Model.displayName</div> // let the user know that its been uploaded 
    @Html.HiddenFor(m => m.FilePath) 
} 
控制器

然後,如果ModelState是有效的,你需要條件的檢查值爲FilePath。如果您提交併且ModelState無效,則FilePath的值現在將包含用戶重新提交時保存文件的路徑。但在ModelState有效初始提交的情況下,FilePath值將是null

您控制器代碼需要(注意,這個假設MyModel實際上是一個視圖模型,你必須包含相關的數據模型對於早在`Html.TextBoxFor文件保存在數據庫中的表

public ActionResult Create(MyModel model) 
{ 
    if (!ModelState.IsValid) 
    { 
     .... // code as above to save temporary file and return the view 
    } 
    // Initialize an instance of your data model 
    var dataModel = new .... // assumes this contains a property byte[] Image 
    if (model.FilePath == null) 
    { 
     // The code above has never run so read from the HttpPostedFileBase property 
     if(model.Image != null && model.Image.ContentLength > 0) { 
     { 
      MemoryStream target = new MemoryStream(); 
      model.Image.InputStream.CopyTo(target); 
      dataModel.Image = target.ToArray(); 
     } 
    } 
    else 
    { 
     // Read from the temporary file 
     dataModel.Image = System.IO.File.ReadAllBytes(filename); 
     .... // Delete the temporary file 
    } 
    // Map other properties of your view model to the data model 
    // Save and redirect 
}