2014-02-26 30 views
1

我在開發MVC應用程序時遇到了一個問題。如何在編輯頁面ASP.NET MVC中爲HttpPostedFileBase創建輸入類型文件?

我開始其用於一個視圖,如簡單的模型:

public class MyModel 
{ 
    public HttpPostedFileBase[] Files { get; set; } 

    public string Name { get; set; } 
} 

我有一個視圖(Create.aspx)

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MyModel>" %> 
... 
    <form method="post" action="/My/Create" enctype = "multipart/form-data"> 
     <input type="file" name="Files" /> 
     ... 
     <%:Html.TextBoxFor(item=>item.Name) %> 
     <input type="submit" value="Create" /> 
    </form> 

控制器:

public class ActionController: Controller { 
    public ActionResult Create() { 
     var myModel = new MyModel(); 
     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Create(MyModel model) { 
     if(ModelState.isValid) { /* save */ } 
    } 

    public ActionResult Edit(int id) { 
     var myModel = _manager.Get(id); 
     myModel.Files = /* what to do here ? */ 

     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Edit(MyModel model) { 
     if(ModelState.isValid) { /* edit */ } 
    } 
} 

我的問題:如何創建要發送的HttpPostedFileBase對象o查看並顯示它們(請參閱下面的編輯頁面)?

這些文件以nvarchar的形式存儲在數據庫中,並具有相對路徑(如標籤)。

我想保存已保存的文件,只需更改名稱字段。

從數據庫中我收到一個存儲文件路徑,文件類型和文件流的對象。

而對於編輯aspx頁面:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MyModel>" %> 
... 
    <form method="post" action="/My/Edit" enctype = "multipart/form-data"> 
     <input type="file" name="Files" /> 
     /* display here the files */ 
     ... 
     <%:Html.TextBoxFor(item=>item.Name) %> 
     <input type="submit" value="Create" /> 
    </form> 

回答

4

你根本無法使用HttpPostedFileBase顯示文件。 作爲其描述說:

用作提供訪問已上載由客戶端單獨的文件類的基類。

它用於訪問正在上傳的文件。如果要顯示已上傳的文件,則必須使用其他方法,例如使用文件方法

0

您可以使用像下面的示例代碼顯示在視圖文件:

public FileContentResult ViewImage(/*parameters*/) 
    { 
     byte[] img = //TODO: take your image as byte array 
     return new FileContentResult(img, "image/jpeg"); 
    } 

,並在您view

<img src="@Url.Action("ViewImage", "ControllerName", new { @*parameters*@ })"> 

但如果你只想預覽上傳之前,你不得不使用一些文件像這樣:

HTML:

<p>Please specify an image file: <input type="file" name="datafile" id="datafile" size="40"></p> 
<div id="preview"><img height="240" /></div> 

JS:

$(function() { 
    $('#datafile').change(function(e) 
     { 
      e.preventDefault(); 
      var f = e.target.files[0]; 
      if(f && window.FileReader) 
      { 
       var reader = new FileReader(); 
       reader.onload = function(evt) { $('#preview>img').attr('src', evt.target.result); }; 
       reader.readAsDataURL(f); 
      } 
     } 
    ); 
}); 

FIDDLE

相關問題