天天看點

JQuery檔案上傳及以Base64字元串形式呈現圖檔

一:上傳之

首先,你必然得有一個 file input,如下:

<td>

    <img id="imgGif" style="display: none" />

    <input type="file" id="imgGifFile" name="imgGifFile" value="選擇圖檔" class="easyui-validatebox"

            data-options="

        @if (ViewBag.IsEdit != true)

        {

        @:required: true,missingMessage:'請選擇課程圖檔!',

        }

        " />

</td>

其次,讓我們 upload,如下:

$.ajaxFileUpload({

    url: '@ViewBag.Domain/Course/CreateUpdate',

    type: 'post',

    data: otherObj,

    secureuri: false,

    fileElementId: 'imgGifFile',

    dataType: 'json',

    success: function (data) {

        $("#courseBank").datagrid("reload");

        if ($("#Id").val() != "") {

            $.messager.alert("提示", "課程修改成功!");

        } else {

            $.messager.alert("提示", "課程添加成功!");

        }

    },

    error: function () {

        window.OnLoadFunc.isSaved();

        $.messager.alert("提示", "伺服器無響應,請稍後重試!");

    }

});

其中,fileElementId 就是我們的 file input 的 Id 值,除此之外,如果我們要同時送出表單資料,則可以建構一個如上的 otherObj,是一個 json 對象。類似如下,

var result = {

    Id: $("#Id").val(),

    CategoryId: $("#categoryTree").tree("getSelected").id,

    Name: $("#name").val};

那麼,服務端代碼如下:

public void CreateUpdate(Course course)

{

    HttpPostedFileBase imgGifFile = Request.Files["imgGifFile"];

    course.ImgGif = ImageHelper.GetImgByte(imgGifFile);

    if (!string.IsNullOrEmpty(course.Id))

    {

        _courseDal.Update(course);

    else

        course.Id = Guid.NewGuid().ToString().Replace("-", string.Empty);

        course.Creator = user.Id;

        _courseDal.Insert(course);

}

伺服器端,首先會自動根據 JSON 内容,構造 Course 對象,但是,檔案需要通過 Request.Files["imgGifFile"]; 來進行擷取的,擷取完畢你就可以轉成二進制存放到資料庫。注意到ImageHelper,為一個幫助類,後面會專門貼出代碼。

二:從資料庫讀出來并轉為base64字元串,并在網頁上呈現出來

先看前台代碼:

$('#imgGif').attr("width", "100px");

$('#imgGif').attr("height", "100px");

$('#imgGif').attr("src", "@ViewBag.ImgGifSrc");

$('#imgGif').show();

$('#imgGif').after("<br/>");

無非就是ImgGifSrc,它是字元串如下:

ViewBag.ImgGifSrc = ImageHelper.Base64ImgToSrc(ViewBag.EditCourse.ImgGif);

現給出ImageHelper:

using System;

using System.Collections.Generic;

using System.Drawing.Imaging;

using System.Globalization;

using System.IO;

using System.Linq;

using System.Reflection;

using System.Text;

using System.Web;

namespace YHBJ.Utility.Web

    public class ImageHelper

        public static byte[] GetImgByte(HttpPostedFileBase imgFileBase)

        {

            if (imgFileBase != null && !string.IsNullOrEmpty(imgFileBase.FileName))

            {

                var len = imgFileBase.ContentLength;

                byte[] bytes = null;

                using (var obj = new BinaryReader(imgFileBase.InputStream))

                {

                    bytes = obj.ReadBytes(len);

                }

                if (bytes.Length > 2)

                    string fileclass = string.Empty;

                    try

                    {

                        fileclass = bytes[0].ToString(CultureInfo.InvariantCulture);

                        fileclass += bytes[1].ToString(CultureInfo.InvariantCulture);

                    }

                    catch

                    }

                    String[] fileType = { "7173", //gif

                                          "255216", //jpg

                                          "6677" //bmp

                                        };

                    var flag = fileType.Any(t => fileclass == t);

                    if (flag)

                        return bytes;

                }

            }

            return null;

        }

        public static string Base64ImgToSrc(byte[] imgBytes)

            if (imgBytes == null)

                return string.Empty;

            using (var stream = new MemoryStream(imgBytes))

                using (var image = System.Drawing.Image.FromStream(stream))

                    return string.Format(

                        "data:image/{0};base64,{1}",

                        GetImageExtension(image),

                        Convert.ToBase64String(imgBytes));

            }

        private static string GetImageExtension(System.Drawing.Image image)

            var imgFormatList = typeof(ImageFormat).GetProperties(BindingFlags.Static | BindingFlags.Public);

            foreach (var item in imgFormatList)

                var imgFormat = (ImageFormat)item.GetValue(null, null);

                if (imgFormat.Guid.Equals(image.RawFormat.Guid))

                    return item.Name.ToLower();

            return "gif";

要注意的是,base64格式的圖檔,有上限限制,預設多少來着,Anyway,bing之。

另,check圖檔格式:

if ($("#imgGifFile").val() != "") {

    var strRegex = "(.gif|.GIF)$"; //用于驗證圖檔擴充名的正規表達式

    var re = new RegExp(strRegex);

    if (!re.test($("#imgGifFile").val())) {

        $.messager.alert("提示", "必須是gif圖檔!");

        return false;

JQuery檔案上傳及以Base64字元串形式呈現圖檔

本文基于

Creative Commons Attribution 2.5 China Mainland License

釋出,歡迎轉載,演繹或用于商業目的,但是必須保留本文的署名

http://www.cnblogs.com/luminji

(包含連結)。如您有任何疑問或者授權方面的協商,請給我留言。