一:上传之

首先,你必然得有一个 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字符串形式呈现图片的更多相关文章

  1. 强大的支持多文件上传的jQuery文件上传插件Uploadify

    支持多文件上传的jQuery文件上传插件Uploadify,目前此插件有两种版本即Flash版本和HTML5版本,对于HTML5版本会比较好的支持手机浏览器,避免苹果手机Safari浏览器不支持Fla ...

  2. jQuery文件上传插件Uploadify(转)

    一款基于flash的文件上传,有进度条和支持大文件上传,且可以多文件上传队列. 这款在flash的基础上增加了html5的支持,所以在移动端也可以使用. 由于官方提供的版本是flash免费,html5 ...

  3. 文件上传三:base64编码上传

    介绍三种上传方式: 文件上传一:伪刷新上传 文件上传二:FormData上传 文件上传三:base64编码上传 Flash的方式也玩过,现在不推荐用了. 优点: 1.浏览器可以马上展示图像,不需要先上 ...

  4. jQuery文件上传插件jQuery Upload File 有上传进度条

    jQuery文件上传插件jQuery Upload File 有上传进度条 jQuery文件上传插件jQuery Upload File,插件使用简单,支持单文件和多文件上传,支持文件拖拽上传,有进度 ...

  5. 20款最好的jQuery文件上传插件

    当它是关于开发网络应用程序和网页的时候,文件上传功能的重要性是不容忽视的.一个文件上传功能可以让你上传所有类型的文件在网站上,包括视频,图像,文件和更多.创建一个文件上传功能,对你的网站是不是很难,有 ...

  6. jQuery 文件上传插件:uploadify、swfupload

    jQuery 文件上传插件: uploadify.swfupload

  7. JQuery文件上传插件JQuery.upload.js的用法简介

    JQuery文件上传插件,这个插件很小,用法很简单,效果却很棒.注意:JQuery版本要求1.8及以上,大家执行如果没效果,则检查JQuery版本,如果是1.8及以上,则该插件源码中的.size()需 ...

  8. 可拖拽和带预览图的jQuery文件上传插件ssi-uploader

    插件描述:ssi-uploader是一款带预览图并且可以拖拽文件的jQuery ajax文件上传插件.该文件上传插件支持AJAX,支持多文件上传,可控制上的文件格式和文件大小,提供各种回调函数,使用非 ...

  9. jquery文件上传控件 Uploadify

    (转自 http://www.cnblogs.com/mofish/archive/2012/11/30/2796698.html) 基于jquery的文件上传控件,支持ajax无刷新上传,多个文件同 ...

随机推荐

  1. GMM与EM算法

    用EM算法估计GMM模型参数 参考  西瓜书 再看下算法流程

  2. CROC 2016 - Elimination Round (Rated Unofficial Edition) E - Intellectual Inquiry dp

    E - Intellectual Inquiry 思路:我自己YY了一个算本质不同子序列的方法, 发现和网上都不一样. 我们从每个点出发向其后面第一个a, b, c, d ...连一条边,那么总的不同 ...

  3. Server sent passive reply with unroutable address. Using server address instead

    最近在linux服务器安装vsftp服务.经过一轮设置,终于可以连接上了,用winSCP连接,刷新目录就提示这个错误. 解决办法: vim /etc/vsftpd.conf  ,编辑配置文件,最后加上 ...

  4. CodeForces - 600C Make Palindrome 贪心

    A string is called palindrome if it reads the same from left to right and from right to left. For ex ...

  5. springmvc遇见406错误的问题分析

    如果springmvc遇到406错误: 90%没有加入Jackson的包 10%因为后缀为.html 10%的情况,解决方案为加多一个映射,使用.action

  6. 支撑大规模公有云的Kubernetes改进与优化 (1)

    Kubernetes是设计用来实施私有容器云的,然而容器作为公有云,同样需要一个管理平台,在Swarm,Mesos,Kubernetes中,基于Kubernetes已经逐渐成为容器编排的最热最主流的平 ...

  7. Kali2.0通过xrdp实现windows远程链接Linux

    标题:Kali2.0通过xrdp实现windows远程链接Linux apt-get install xrdp 首先需要安装xrdp 接下来安装xfce4 apt-get install xfce4 ...

  8. poj 3463 次短路

    题意:给定一个有向图,问从起点到终点,最短路+比最短路距离长1的路的个数. 当年数据结构课程设计用A*做过,现在忘光了,2333 #include<stdio.h> #include< ...

  9. 【10.7校内测试】【队列滑窗】【2-sat】【贪心+栈二分+线段树(noip模拟好题)】【生日祭!】

    比较好想的一道题,直接用队列滑窗,因为扫一遍往队列里加东西时,改变的只有一个值,开桶储存好就行了! #include<bits/stdc++.h> using namespace std; ...

  10. opencv第一课 打开一个图片

    #include<stdio.h>#include<stdlib.h>#include<opencv2\opencv.hpp>#include<iostrea ...