ASP.NET MVC3上傳檔案方式

ASP.NET MVC3上傳檔案方式

使用ASP.NET MVC上傳附件就是要把form的 enctype設定成"multipart/form-data"

說明如下,

我們定義一個ModelClass為UploadTest


using System.Web.Mvc;

namespace SkyPea.WebUI.Models
{
    public class UploadTest
    {
        public int ProductId { get; set; }
        public byte[] ImageData { get; set; }
        [HiddenInput(DisplayValue = false)]
        public string ImageMimeType { get; set; }
    }
}

HomeController為


{
    private UploadTest product = new UploadTest();

    // GET: /Home/
    [Authorize]
    public ActionResult Index()
    {
        product.ProductId = 1;
        return View(product);
    }

    [HttpPost]
    public ActionResult Edit(UploadTest product, HttpPostedFileBase image)
    {
        product.ProductId = 1;
        if (image != null)
        {
            product.ImageMimeType = image.ContentType;
            product.ImageData = new byte[image.ContentLength];
            image.InputStream.Read(product.ImageData, 0, image.ContentLength);
            image.SaveAs(Server.MapPath(@"~/Logs/") + product.ProductId.ToString() + ".jpg");
        }
        
        return RedirectToAction("Index");
    }

    public FileContentResult GetImage(int productId)
    {
        string fileName = Server.MapPath(@"~/Logs/") + productId.ToString() + ".jpg";
        if (System.IO.File.Exists(fileName))
        {
               
            using(System.IO.FileStream fs = System.IO.File.OpenRead(fileName)){
                long fileLen = fs.Length;
                byte[] fsArray = new Byte[fileLen];
                fs.Read(fsArray, 0, (int)fileLen);
                return File(fsArray, "image/jpeg");
            }
        }
        else
        {
            return null;
        }
    }

}

如下view,



@{
    ViewBag.Title = "Index";
}

<h1>Upload File Test</h1>
@using (Html.BeginForm( "Edit", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="editor-label">Image</div>
<div class="editor-field">
 
    <img width="150" height="150" src="@Url.Action("GetImage", "Home", new { Model.ProductId })" />
 
<div>Upload new image: <input type="file" name="Image" /></div>
</div>
<input type="submit" value="Save" />
}

所以選取好圖檔後,按下Save就會呼叫Controller中的Save,將檔案存起來後,再轉到Index。

MVC3_UPLOAD

Hi, 

亂馬客Blog已移到了 「亂馬客​ : Re:從零開始的軟體開發生活

請大家繼續支持 ^_^