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)";//varre=newRegExp(strRegex);if(!re.test(("#imgGifFile").val())) {
        $.messager.alert("提示", "必须是gif图片!");
        return false;
    }
}

posted @   陆敏技  阅读(7782)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
Web Counter
Coupon for Contacts
点击右上角即可分享
微信分享提示