MVC保存二進制到數據庫,並顯示文件的方法(圖片顯示)


通過兩篇文章解決了數據庫存儲圖片並顯示到View的方法:

http://blog.sina.com.cn/s/blog_6da396a50101639u.html
http://www.cnblogs.com/artech/archive/2012/08/14/action-result-02.html

其中,第一篇雖然有些混亂,但是對我有很大啟發,而的第二篇寫的就很籠統卻比較了然,大體看一下就解決了令我不解的顯示方法。

 

1.當然第一步是Img,我們在View里,給Img的文件來源,加上Action調用:

  <img src=@Url.Action("GetImg", new { id = iii.DrId }) />

iii就是我們的對象實例了,這里,我們調用的是當前Controller的GetImg。

2.所以我們之后需要一個Action:

/// <summary>
/// Action:獲取圖片文件
/// </summary>
public FileContentResult GetImg(int id)
{
    var anModel = zService.Find(id);
    if (anModel != null)
    {
       return File(anModel.DrImg, "image/jpg", anModel.DrId.ToString() + anModel.DrName);
    }
    else
    {
        return null;
    }
}

這里的方法就是拷貝的我最開始提供的文章里的,並未有太多修改,注意一下“File”方法,有三個參數:

FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName)

第一個當然就是讀取出來的文件數據了,第二個是要以什么類型展示文件(MimeType),第三個就是要展示到頁面的文件,是什么文件名
這里要注意的是,參數3,如果這樣自定義的名字,生成的結果好像是:『Id+Name+"~序號"』比如:361我是超人~3.jpg


3.至於怎么存進數據庫,其實在鏈接文章1里有講解,我用的是MVC和EF,代碼就會類似於這樣:

3.1前台,View里加Form,注意“enctype”屬性,看網上的幾個文章,都說要加這個。

@using (Html.BeginForm("Add", "DoctorAdmin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <fieldset>
        <legend>DoctorInfo</legend>

        <div class="editor-label">
            <span>圖片</span>
        </div>
        <div>
            <input type="file" name="imgs" />
        </div>
                
        <div class="editor-label">
            @Html.LabelFor(model => model.DrName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.DrName)
        </div>

        <p>
            <input type="submit" value="確定" />
        </p>
    </fieldset>
}

 

3.2后台,Action和一個獲取圖片方法。

        [HttpPost]
        public ActionResult Add(WXG_Doctor pModel)
        {
            if (pModel == null)
            {
                return HttpNotFound();
            }

            //獲取上傳圖片
            HttpPostedFileBase file1 = Request.Files[0];
            int error1;
            pModel.DrImg = FileUpDown.GetImageByte(out error1, file1, 1024 * 1024);

            zService.Create(pModel);
            return RedirectToAction("Add");
        }



        /// <summary>
        /// 獲取圖片內容
        /// </summary>
        ///<param name="pError">0:正常完成 1:文件大小異常。2:擴展名不支持。</param>
        /// <param name="pUpImage">要上傳的文件</param>
        /// <param name="pFileLength">文件要小於這個大小</param>
        /// <returns>圖片文件的內容</returns>
        public static byte[] GetImageByte(out int pError, HttpPostedFileBase pUpImage, int pFileLength)
        {
            if (pUpImage.FileName != null)
            {
                //要上傳的文件大小判斷
                int sFileLength = pUpImage.ContentLength;
                if (sFileLength < 1 || sFileLength > pFileLength)
                {
                    pError = 1;
                    return null;
                }

                //獲取文件名
                string sFilename = System.IO.Path.GetFileName(pUpImage.FileName).ToLower();
                //獲取upImage文件的擴展名
                string extendName = System.IO.Path.GetExtension(sFilename);
                //判斷是否為圖片格式 
                if (extendName != ".jpg" && extendName != ".jpeg" && extendName != ".gif" && extendName != ".bmp" && extendName != ".png")
                {
                    pError = 2;
                    return null;
                }

                byte[] myData = new Byte[sFileLength];
                pUpImage.InputStream.Read(myData, 0, sFileLength);
                pError = 0;
                return myData;
            }
            else
            {
                pError = 3;
                return null;
            }
        }
    }

其中,返回的狀態那個參數,我不知會不會寫的很2,而且具體的邏輯也缺乏健壯,請大家不要直接拿來就用了,酌情修改下。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM