asp.net+easyui框架上传图片之前判断图片格式及预览

上传图片功能虽然很简单,但是在上传图片之前验证图片的格式,并同时实现预览,还是有很多细节需要注意的,本文的就详细来解说这个。

html页面

<div>  
    选择图片:<input id="idFile" style="width:224px" runat="server" name="pic" onchange="javascript:setImagePreview(this,localImag,preview);" type="file" />  
</div>  
    预  览:  
<div id="localImag">  
    <%--预览,默认图片--%>  
    <img id="preview" alt="预览图片" onclick="over(preview,divImage,imgbig);" src="img/5691.jpg" style="width: 400px; height: 400px;"/>   
</div>  

js代码

<script>  
    //检查图片的格式是否正确,同时实现预览  
    function setImagePreview(obj, localImagId, imgObjPreview) {  
        var array = new Array('gif', 'jpeg', 'png', 'jpg', 'bmp'); //可以上传的文件类型  
        if (obj.value == '') {  
            $.messager.alert("让选择要上传的图片!");  
            return false;  
        }  
        else {  
            var fileContentType = obj.value.match(/^(.*)(\.)(.{1,8})$/)[3]; //这个文件类型正则很有用   
            ////布尔型变量  
            var isExists = false;  
            //循环判断图片的格式是否正确  
            for (var i in array) {  
                if (fileContentType.toLowerCase() == array[i].toLowerCase()) {  
                    //图片格式正确之后,根据浏览器的不同设置图片的大小  
                    if (obj.files && obj.files[0]) {  
                        //火狐下,直接设img属性   
                        imgObjPreview.style.display = 'block';  
                        imgObjPreview.style.width = '400px';  
                        imgObjPreview.style.height = '400px';  
                        //火狐7以上版本不能用上面的getAsDataURL()方式获取,需要一下方式   
                        imgObjPreview.src = window.URL.createObjectURL(obj.files[0]);  
                    }  
                    else {  
                        //IE下,使用滤镜   
                        obj.select();  
                        var imgSrc = document.selection.createRange().text;  
                        //必须设置初始大小   
                        localImagId.style.width = "400px";  
                        localImagId.style.height = "400px";  
                        //图片异常的捕捉,防止用户修改后缀来伪造图片   
                        try {  
                            localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";  
                            localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;  
                        }  
                        catch (e) {  
                            $.messager.alert("您上传的图片格式不正确,请重新选择!");  
                            return false;  
                        }  
                        imgObjPreview.style.display = 'none';  
                        document.selection.empty();  
                    }  
                    isExists = true;  
                    return true;  
                }  
            }  
            if (isExists == false) {  
                $.messager.alert("上传图片类型不正确!");  
                return false;  
            }  
            return false;  
        }  
    }  
 
        //显示图片    
        function over(imgid, obj, imgbig) {  
            //大图显示的最大尺寸  4比3的大小  400 300    
            maxwidth = 400;  
            maxheight = 300;  
 
            //显示    
            obj.style.display = "";  
            imgbig.src = imgid.src;  
 
            //1、宽和高都超过了,看谁超过的多,谁超的多就将谁设置为最大值,其余策略按照2、3    
            //2、如果宽超过了并且高没有超,设置宽为最大值    
            //3、如果宽没超过并且高超过了,设置高为最大值    
 
            if (img.width > maxwidth && img.height > maxheight) {  
                pare = (img.width - maxwidth) - (img.height - maxheight);  
                if (pare >= 0)  
                    img.width = maxwidth;  
                else  
                    img.height = maxheight;  
            }  
            else if (img.width > maxwidth && img.height <= maxheight) {  
                img.width = maxwidth;  
            }  
            else if (img.width <= maxwidth && img.height > maxheight) {  
                img.height = maxheight;  
            }  
        }  
</script>  

界面效果

 
                </div>  
           </td>  
       </tr>  
    </table>  
        <input type="hidden" id="test" name="test" />   
        <div style="width:300px; text-align:center;">  
            <a href="javascript:void(0)" class="easyui-linkbutton" onclick="submitForm()">确定</a>  
        <a href="javascript:void(0)" class="easyui-linkbutton" onclick="clearForm()">取消</a>  
        </div>   
        <%--显示大图标的区域--%>    
        <div id="divImage" style="display: none;left:365px;top:40px;position: absolute">    
            <img id="imgbig" onclick="out();" src="" alt="大图" />    
        </div>    
    </div>  
    </form>  

JS代码:

         
  //显示图片    
        function over(imgid, obj, imgbig) {  
            //大图显示的最大尺寸  4比3的大小  400 300    
            maxwidth = 400;  
            maxheight = 300;  
 
 
            //显示    
            obj.style.display = "";  
            imgbig.src = imgid.src;  
 
 
            //1、宽和高都超过了,看谁超过的多,谁超的多就将谁设置为最大值,其余策略按照2、3    
            //2、如果宽超过了并且高没有超,设置宽为最大值    
            //3、如果宽没超过并且高超过了,设置高为最大值    
 
 
            if (img.width > maxwidth && img.height > maxheight) {  
                pare = (img.width - maxwidth) - (img.height - maxheight);  
                if (pare >= 0)  
                    img.width = maxwidth;  
                else  
                    img.height = maxheight;  
            }  
            else if (img.width > maxwidth && img.height <= maxheight) {  
                img.width = maxwidth;  
            }  
            else if (img.width <= maxwidth && img.height > maxheight) {  
                img.height = maxheight;  
            }  
        }  
 
 
        //隐藏图片    
        function out() {  
            document.getElementById('divImage').style.display = "none";  
        }  
 
 //保存信息  
        function submitForm() {  
            $.messager.confirm('提示', '你确定要添加此记录吗?', function (r) {  
                if (r) {  
                    //先上传图片后,再提交  
                    upLoadFile();  
 
                    var test = document.getElementById("test").value = "add";  
                    var paintingName = document.getElementById("paintingName").value;  
                    var artistID = document.getElementById("ddlist").value;  
                    var type = $(":checkbox[name='type']").attr("checked") == true ? "书法" : "国画";  
                    var price = document.getElementById("price").value;  
                    var height = document.getElementById("height").value;  
                    var width = document.getElementById("width").value;  
                    var idFile = document.getElementById("idFile").value;  
 
                    //先判断是否上传图片之后在提交  
 
                    $('#ff').form('submit', {  
                        url: "Painting.ashx?paintingName=" + paintingName + "&artistID=" + artistID +  
                             "&type=" + type + "&price=" + price + "&height=" + height + "&width=" + width +  
                            "&idFile=" + idFile + "&addID=" + addID + "&test=" + test,  
                        dataType: "json",  
                        onSubmit: function () {  
                            return $(this).form('validate');  
                        },  
                        success: function (result) {  
                            if (result == "T") {  
                                //清空文本框  
                                document.getElementById("paintingName").value = "";  
                                document.getElementById("price").value = "";  
                                document.getElementById("height").value = "";  
                                document.getElementById("width").value = "";  
                                document.getElementById("idFile").value = "";  
                                document.getElementById("preview").value = "";  
                                $.messager.alert('提示', '恭喜您,信息添加成功!', 'info');  
                            }  
                            else {  
                                $.messager.alert('提示', '保存失败,请您核对!', 'info');  
                            }  
                        }  
                    });  
                }  
            });  
        }  
 
        //上传图片  
        function upLoadFile() {  
            var idFile = document.getElementById("idFile").value;  
            //判断是否选择图片  
            if (idFile == null || idFile == "") {  
                $.messager.alert('提示','请添加图片!');  
                document.getElementById("idFile").focus();  
                document.getElementById("idFile").select();  
                return;  
            }  
            var options = {  
                type: "POST",  
                url: 'Files.ashx',  
                //success: showResponse  
            };  
            // 将options传给ajaxForm  
            $('#ff').ajaxSubmit(options);  
        }  
        //function showResponse() {  
        //    alert("上传成功!");  
        //}  
 
 
        function clearForm(){  
           //清空文本框  
           document.getElementById("paintingName").value = "";  
           document.getElementById("price").value = "";  
           document.getElementById("height").value = "";  
           document.getElementById("width").value = "";  
           document.getElementById("idFile").value = "";  
         }  

后台一般处理程序的代码:

上传图片的一般处理程序:

<span style="font-size:14px;"> /// <summary>  
    /// Files 的摘要说明  
    /// </summary>  
    public class Files : IHttpHandler  
    {  
 
        public void ProcessRequest(HttpContext context)  
        {  
            context.Response.ContentType = "text/plain";  
            //图片名  
            HttpFileCollection files = context.Request.Files;  
            if (files.Count > 0)  
            {  
                for (int i = 0; i < files.Count; i++)  
                {  
                    HttpPostedFile file = files[i];  
 
                    if (file.ContentLength > 0)  
                    {  
                        //全路径  
                        string FullFullName = file.FileName;  
                        //获取图片的名称  
                        String fileName = FullFullName.Substring(FullFullName.LastIndexOf("\\") + 1);  
                        //保存路径D:\GoodCommunitySystem2.0 - 副本\GoodCommunitySystem\Paint\img\  
                        string path = "~/Paint/img";  
                        file.SaveAs(System.Web.HttpContext.Current.Server.MapPath(path) + "\\" + fileName);  
                    }  
                }  
            }  
        }  
 
        public bool IsReusable  
        {  
            get  
            {  
                return false;  
            }  
        }  
    }</span>  

提交表单的一般处理程序:

/// <summary>  
  /// Painting 的摘要说明  
  /// </summary>  
  public class Painting : IHttpHandler  
  {  
      paintingBLL paintingbll = new paintingBLL();  
 
      Entity.paintingEntity paintingEntity = new Entity.paintingEntity();  
 
      public void ProcessRequest(HttpContext context)  
      {  
          context.Response.ContentType = "text/plain";  
          string command = context.Request["test"].ToString();//前台传的标示值  
          if (command == "add")  
          {  
              Add(context);  
          }  
      }  
      /// <summary>  
      /// 添加记录  
      /// </summary>  
      /// <param name="context"></param>  
      public void Add(HttpContext context)  
      {  
 
          paintingEntity.PaintingName = context.Request.QueryString["paintingName"];  
          paintingEntity.PaintingStyle = context.Request.QueryString["type"];  
          paintingEntity.PaintingURL = context.Request.QueryString["idFile"];  
          paintingEntity.Price = Convert.ToInt32(context.Request["price"]);  
          paintingEntity.AddID = Convert.ToInt32(context.Request["addID"]);  
          paintingEntity.ArtistID = Convert.ToInt32(context.Request["artistID"]);  
          paintingEntity.Height = Convert.ToInt32(context.Request.QueryString["height"]);  
          paintingEntity.Width = Convert.ToInt32(context.Request.QueryString["width"]);  
          try  
          {  
              if (paintingbll.Add(paintingEntity))  
              {  
                  context.Response.Write("T");  
              }  
              else  
              {  
                  context.Response.Write("F");  
              }  
          }  
 
          catch (Exception ex)  
          {  
              throw ex;  
          }  
      }  
      public bool IsReusable  
      {  
          get  
          {  
              return false;  
          }  
      }  
  }  

需要引入的js:

<%--基础样式--%>  
<link href="../../themes/default/easyui.css" rel="stylesheet" />  
<%--图标样式--%>  
<link href="../../themes/icon.css" rel="stylesheet" />  
 <%--easyui-js--js的文件有先有后min.js必须在前,easyui.min.js必须在后--%>  
<script src="../jquery.min.js"></script>  
<%--easyui 的js--%>  
<script charset="utf-8" src="../jquery.easyui.min.js"></script>  
<%--中文js--%>  
<script src="../locale/easyui-lang-zh_CN.js"></script>  
 
<%--上传图片时js--%>  
<script src="js/jquery.form.js"></script>  

     上传图片时,需要jquery.form.js的js文件,下载地址:http://plugins.jquery.com/form/

=================================================================================

  最近有网友,总觉得看的还不是太明白,能不能将paintingBLL和paintingEntity代码贴一下-----新人求罩,我个人觉得实体层就没有必要了,下面我就将paintingBLL的源码粘一下,仅供大家参考。

using System;  
using System.Data;  
using System.Collections.Generic;  
using Common;  
using Entity;  
using DALFactory;  
using IDAL;  
namespace BLL  
{  
    /// <summary>  
    /// paintingBLL  
    /// </summary>  
    public partial class paintingBLL  
    {  
        private readonly IpaintingDAL dal=DataAccess.CreatepaintingDAL();  
        public paintingBLL()  
        {}  
        #region  BasicMethod  
 
        /// <summary>  
        /// 得到最大ID  
        /// </summary>  
        public int GetMaxId()  
        {  
            return dal.GetMaxId();  
        }  
 
        /// <summary>  
        /// 是否存在该记录  
        /// </summary>  
        public bool Exists(int PaintingID)  
        {  
            return dal.Exists(PaintingID);  
        }  
 
        /// <summary>  
        /// 增加一条数据  
        /// </summary>  
        public bool Add(Entity.paintingEntity Entity)  
        {  
            return dal.Add(Entity);  
        }  
 
        /// <summary>  
        /// 更新一条数据  
        /// </summary>  
        public bool Update(Entity.paintingEntity Entity)  
        {  
            return dal.Update(Entity);  
        }  
 
        /// <summary>  
        /// 删除一条数据  
        /// </summary>  
        public bool Delete(int PaintingID)  
        {  
              
            return dal.Delete(PaintingID);  
        }  
        /// <summary>  
        /// 删除一条数据  
        /// </summary>  
        public bool DeleteList(string PaintingIDlist )  
        {  
            return dal.DeleteList(PaintingIDlist );  
        }  
 
        /// <summary>  
        /// 得到一个对象实体  
        /// </summary>  
        public Entity.paintingEntity GetEntity(int PaintingID)  
        {  
              
            return dal.GetEntity(PaintingID);  
        }  
 
        /// <summary>  
        /// 得到一个对象实体,从缓存中  
        /// </summary>  
        public Entity.paintingEntity GetEntityByCache(int PaintingID)  
        {  
              
            string CacheKey = "paintingEntityEntity-" + PaintingID;  
            object objEntity = Common.DataCache.GetCache(CacheKey);  
            if (objEntity == null)  
            {  
                try  
                {  
                    objEntity = dal.GetEntity(PaintingID);  
                    if (objEntity != null)  
                    {  
                        int EntityCache = Common.ConfigHelper.GetConfigInt("EntityCache");  
                        Common.DataCache.SetCache(CacheKey, objEntity, DateTime.Now.AddMinutes(EntityCache), TimeSpan.Zero);  
                    }  
                }  
                catch{}  
            }  
            return (Entity.paintingEntity)objEntity;  
        }  
 
        /// <summary>  
        /// 获得数据列表  
        /// </summary>  
        public DataSet GetList(string strWhere)  
        {  
            return dal.GetList(strWhere);  
        }  
 
        /// <summary>  
        /// 获得数据列表  
        /// </summary>  
        public DataSet GetPaintingList(string strWhere)  
        {  
            return dal.GetPaintingList(strWhere);  
        }  
        /// <summary>  
        /// 获得前几行数据  
        /// </summary>  
        public DataSet GetList(int Top,string strWhere,string filedOrder)  
        {  
            return dal.GetList(Top,strWhere,filedOrder);  
        }  
        /// <summary>  
        /// 获得数据列表  
        /// </summary>  
        public List<Entity.paintingEntity> GetEntityList(string strWhere)  
        {  
            DataSet ds = dal.GetList(strWhere);  
            return DataTableToList(ds.Tables[0]);  
        }  
        /// <summary>  
        /// 获得数据列表  
        /// </summary>  
        public List<Entity.paintingEntity> DataTableToList(DataTable dt)  
        {  
            List<Entity.paintingEntity> EntityList = new List<Entity.paintingEntity>();  
            int rowsCount = dt.Rows.Count;  
            if (rowsCount > 0)  
            {  
                Entity.paintingEntity Entity;  
                for (int n = 0; n < rowsCount; n++)  
                {  
                    Entity = dal.DataRowToEntity(dt.Rows[n]);  
                    if (Entity != null)  
                    {  
                        EntityList.Add(Entity);  
                    }  
                }  
            }  
            return EntityList;  
        }  
 
        /// <summary>  
        /// 获得数据列表  
        /// </summary>  
        public DataSet GetAllList()  
        {  
            return GetList("");  
        }  
 
        /// <summary>  
        /// 分页获取数据列表  
        /// </summary>  
        public int GetRecordCount(string strWhere)  
        {  
            return dal.GetRecordCount(strWhere);  
        }  
        /// <summary>  
        /// 分页获取数据列表  
        /// </summary>  
        public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)  
        {  
            return dal.GetListByPage( strWhere,  orderby,  startIndex,  endIndex);  
        }  
        /// <summary>  
        /// 分页获取数据列表  
        /// </summary>  
        //public DataSet GetList(int PageSize,int PageIndex,string strWhere)  
        //{  
            //return dal.GetList(PageSize,PageIndex,strWhere);  
        //}  
 
        #endregion  BasicMethod  
        #region  ExtensionMethod  
 
        #endregion  ExtensionMethod  
    }  
}  

时间: 2024-10-25 06:03:30

asp.net+easyui框架上传图片之前判断图片格式及预览的相关文章

base-关于Base64上传图片如何判断图片格式等规范

问题描述 关于Base64上传图片如何判断图片格式等规范 base64编码后再用它解码,传过来的图片是否符合规范,或者传过来的图片对不对该怎么办?求大神指导 解决方案 无论什么方式,都只能上传后才能判断,除非客户端不是浏览器而是一个本地程序. 解决方案二: 是后台用base64解码的时候,解完码我看大部分例子上都是用下面这个调整异常,我现在想在里面加个判断 // Base64解码 byte[] b = new BASE64Decoder().decodeBuffer(imgStr); for (

基于ASP.NET+easyUI框架实现图片上传功能(判断格式+即时浏览 )_实用技巧

基于ASP.Net +easyUI框架上传图片,判断格式+实现即时浏览,具体内容如下 <div> 选择图片:<input id="idFile" style="width:224px" runat="server" name="pic" onchange="javascript:setImagePreview(this,localImag,preview);" type="fil

基于ASP.NET+easyUI框架实现图片上传功能(表单)_实用技巧

基于ASP.Net +easyUI框架上传图片,实现图片上传,提交表单: <body> <link href="../../Easyui/themes/easyui.css" rel="stylesheet" type="text/css" /> <script charset="utf-8" src="../../Easyui/jquery.easyui.min.js" ty

基于ASP.NET+EasyUI框架实现图片上传提交表单功能(js提交图片)_实用技巧

我的风格,先给大家展示下效果图,具体效果图如下所示,如果大家感觉还不错很满意请参考实现代码. HTML的代码: <form id="ff" runat="server" method="post"> <div id="content" style="margin-left:50px;"> <table style="width:300px;" id=&quo

asp.net实现上传图片时判断图片的模式GRB或CMYK的方法_实用技巧

本文实例讲述了asp.net实现上传图片时判断图片的模式GRB或CMYK的方法.分享给大家供大家参考,具体如下: Bitmap bmp = new Bitmap(allow_fileStream); //文件路径 allowUpload = stringHelper.IsCMYK(bmp) == "true" ? false : true; //返回true字符串则图片不是RGB模式的 public string IsCMYK(System.Drawing.Image img) { s

PHP判断图片格式的七种方法小结_php技巧

使用php判断文件图片的格式 复制代码 代码如下: <?php $imgurl = "http://www.jb51.net/images/logo.gif"; //方法1 echo $ext = strrchr($imgurl,'.'); echo '<hr>'; //方法2 echo $ext1 = substr($imgurl,strrpos($imgurl, '.')); echo '<hr>'; //方法3 echo(@end(explode(&

php判断图片格式各种方法总结

php中如何判断图片格式,下面给出一种较为简便的方法: 第一种思想方法就是把图片路径当作字符串来处理,那么判断图片格式的也就是变成了查找.号的字符串  代码如下 复制代码 $file= "test.jpg"; $filetype= strtolower(strrchr($file,".")); $arrtype = array(".jpeg",".bmp",".gif",".jpg");

Ajax上传图片及上传前先预览功能实例代码

手头上有几个小项目用到了easyUI,一开始决定使用easyUI就注定了项目整体上前后端分离,基本上所有的请求都采用Ajax来完成.在文件上传的时候用到了Ajax上传文件,以及图片在上传之前的预览效果,解决了这两个小问题,和小伙伴们分享下. 上传之前的预览 方式一 先来说说图片上传之前的预览问题.这里主要采用了HTML5中的FileReader对象来实现,关于FileReader对象,如果小伙伴们不了解,可以查看这篇文章HTML5学习之FileReader接口.我们来看看实现方式: <!DOCT

JavaScript 图片上传预览效果

图片上传预览是一种在图片上传之前对图片进行本地预览的技术. 使用户选择图片后能立即查看图片,而不需上传服务器,提高用户体验. 但随着浏览器安全性的提高,要实现图片上传预览也越来越困难. 不过群众的智慧是无限的,网上已经有很多变通或先进的方法来实现. 例如ie7/ie8的滤镜预览法,firefox 3的getAsDataURL方法. 但在opera.safari和chrome还是没有办法实现本地预览,只能通过后台来支持预览. 在研究了各种预览方法后,作为总结,写了这个程序,跟大家一起分享. 上次写