当前位置:Gxlcms > html代码 > 美观的单张上传控件一个页面可以实例化多个_html/css_WEB-ITnose

美观的单张上传控件一个页面可以实例化多个_html/css_WEB-ITnose

时间:2021-07-01 10:21:17 帮助过:17人阅读

首先需要引用 js 和css

1 2     

Img_List.js 如下:

 1 ///  2 //显示 3 function imgshow(obj) { 4     //$(obj).find("a").show(); 5 } 6  7 //隐藏 8 function imghide(obj) { 9     //$(obj).find("a").hide();10 }11 12 //上传13 function upload() { 14     $("#FileLoad").click();15 }16 17 //删除18 function imgdel(listId, FileId, hfId) {19     20     $.post("/CommonModule/ashx/public.ashx?action=DelMessageImg&Files=" + $("#" + hfId).val(), function (result) {21         if (result != "ok")22             $.messager.alert("消息提示", "删除失败!");23      });24     var html = "
  • "25 $("#"+listId).html(html);26 }27 28 //添加成功29 function imgaddhtml(data, code,listId,fileId,hfId) {30 var list = data.split(',');31 var html = "
  • ";32 html += "
  • ";33 $("#" + listId).html(html);34 }35 36 //图片文件上传37 //uppath 上传空间id 38 //上传成功存放的图片路径的隐藏域id39 //listId 显示图片的区域id40 function ImgUpload(uppath, hndimg,listId) {41 var sendUrl = "/CommonModule/ashx/Upload_Ajax.ashx?action=SingleFile&IsThumbnail=1&UpFilePath=" + uppath;42 //开始提交43 $("#form1").ajaxSubmit({44 beforeSubmit: function (formData, jqForm, options) {45 //alert(1);46 },47 success: function (data, textStatus) {48 var list = $("#" + hndimg).val();49 $("#" + hndimg).val(data.msgbox);50 imgaddhtml(data.msgbox, 0,listId,uppath,hndimg);51 },52 error: function (data, status, e) {53 alert("上传失败!");54 },55 url: sendUrl,56 type: "post",57 dataType: "json",58 timeout: 60000059 });60 };

    Img_List.css 如下:

    1 .img_list{ margin:0px; padding:0px;  overflow:hidden;}2 .img_list ul,.img_list ul li{ margin:0px; padding:0px;} 3 .img_list ul li{ float:left; list-style:none; position:relative; margin:5px 0px 0px 5px;}4 .img_list ul li span5 { position:absolute;top:3px; right:3px; width: 16px; height: 16px; opacity: 0.6;filter: alpha(opacity=60); margin: 0 0 0 2px;6 vertical-align: top; background: url('/Themes/Images/panel_tools.png') no-repeat -16px 0px;}7 .img_list ul li img{ width:80px; height:80px; cursor:pointer; position:relative; z-index:0;}8 .img_list ul li .input{ width:80px; height:80px; cursor:pointer; position:relative; left:-100px;vertical-align: top; margin:0px; padding:0px; opacity:0;filter: alpha(opacity=0); }

    panel_tools.png 如下:

    jia.jpg 如下:

    以上素材引用完成后 再看 前台页面代码:

     1  2                         图片1: 3                          4                              5                              6                             建议尺寸(243*150) 7                          8                      9 10 11                         图片2:12                         13                             14                           15                             16                              建议尺寸(243*150)17                         18                     

    后台页面代码 (初始化控件) :

     1  protected void Page_Load(object sender, EventArgs e) 2         { 3            4             if (!IsPostBack) 5             { 6                ltrimg_list.Text = UpLoad.showUploadFile("File1", "ImgPath", mfmodel.ImgPath, "img_list1"); 7                 Literal1.Text = UpLoad.showUploadFile("File2", "hkImgPath", mfmodel.hkImgPath, "img_list2"); 8                     9             }10         }

    生成上传控件方法

     1   ///  2         /// 生成一个上传插件信息 3         ///  4         /// 上传控件id 5         /// 隐藏域id用来保存上传的图片路径 6         /// 初始化显示的图片地址 7         /// 上传成功之后用来显示上传图片的标签id 8         ///  9         public static string showUploadFile(string fileId, string hfId, string imgUrl, string listId)10         {11             string result = "";12             if (!string.IsNullOrEmpty(imgUrl))13             {14                 result = "
    ";15 }16 else17 {18 result = "
    ";19 }20 21 return result;22 }

    上传文件的方法ashx:

      1 using System;  2 using System.Collections;  3 using System.Collections.Generic;  4 using System.IO;  5 using System.Linq;  6 using System.Text.RegularExpressions;  7 using System.Web;  8 using DotNet.Kernel.Common;  9 using DotNet.Utilities; 10 using LitJson; 11  12 namespace BPMS.WEB.Admin.ashx 13 { 14     ///  15     /// Upload_Ajax 的摘要说明 16     ///  17     public class Upload_Ajax : IHttpHandler 18     { 19  20         public void ProcessRequest(HttpContext context) 21         { 22             //取得处事类型 23             string action = context.Request.QueryString["action"]; 24  25             switch (action) 26             { 27                 case "SingleFile": //单文件 28                     SingleFile(context); 29                     break; 30                 case "MultipleFile": //多文件 31                     MultipleFile(context); 32                     break; 33                 case "AttachFile": //附件 34                     AttachFile(context); 35                     break; 36                 case "EditorFile": //编辑器文件 37                     EditorFile(context); 38                     break; 39  40             } 41         } 42  43  44  45         #region 上传单文件处理=================================== 46         private void SingleFile(HttpContext context) 47         { 48  49             string _refilepath = context.Request.QueryString["ReFilePath"]; //取得返回的对象名称 50             string _upfilepath = context.Request.QueryString["UpFilePath"]; //取得上传的对象名称 51             string _delfile = context.Request.QueryString[_refilepath]; 52             HttpPostedFile _upfile = null; 53             try 54             { 55                 _upfile = context.Request.Files[_upfilepath]; 56             } 57             catch (Exception e) 58             { 59                 context.Response.Write("{\"msg\": \"0\", \"msgbox\": \"上传文件过大!\"}"); 60                 context.Response.End(); 61             } 62             bool _iswater = false; //默认不打水印 63             bool _isthumbnail = false; //默认不生成缩略图 64             bool _isimage = false; 65  66             if (context.Request.QueryString["IsWater"] == "1") 67                 _iswater = true; 68             if (context.Request.QueryString["IsThumbnail"] == "1") 69                 _isthumbnail = true; 70             if (context.Request.QueryString["IsImage"] == "1") 71                 _isimage = true; 72  73             if (_upfile == null) 74             { 75                 context.Response.Write("{\"msg\": \"0\", \"msgbox\": \"请选择要上传文件!\"}"); 76                 return; 77             } 78             UpLoad upFiles = new UpLoad(); 79             string msg = upFiles.fileSaveAs(_upfile, _isthumbnail, _iswater, _isimage); 80             //删除已存在的旧文件 81             Utils.DeleteUpFile(_delfile); 82             //返回成功信息 83             context.Response.Write(msg); 84  85             context.Response.End(); 86         } 87         #endregion 88  89         #region 上传多文件处理=================================== 90         private void MultipleFile(HttpContext context) 91         { 92             string _upfilepath = context.Request.QueryString["UpFilePath"]; //取得上传的对象名称 93             HttpPostedFile _upfile = context.Request.Files[_upfilepath]; 94             bool _iswater = false; //默认不打水印 95             bool _isthumbnail = false; //默认不生成缩略图 96  97             if (context.Request.QueryString["IsWater"] == "1") 98                 _iswater = true; 99             if (context.Request.QueryString["IsThumbnail"] == "1")100                 _isthumbnail = true;101 102             if (_upfile == null)103             {104                 context.Response.Write("{\"msg\": \"0\", \"msgbox\": \"请选择要上传文件!\"}");105                 return;106             }107             UpLoad upFiles = new UpLoad();108             string msg = upFiles.fileSaveAs(_upfile, _isthumbnail, _iswater);109             //返回成功信息110             context.Response.Write(msg);111             context.Response.End();112         }113         #endregion114 115         #region 上传附件处理=====================================116         private void AttachFile(HttpContext context)117         {118             string _upfilepath = context.Request.QueryString["UpFilePath"]; //取得上传的对象名称119             HttpPostedFile _upfile = context.Request.Files[_upfilepath];120             bool _iswater = false; //默认不打水印121             bool _isthumbnail = false; //默认不生成缩略图122 123             if (_upfile == null)124             {125                 context.Response.Write("{\"msg\": \"0\", \"msgbox\": \"请选择要上传文件!\"}");126                 return;127             }128             UpLoad upFiles = new UpLoad();129             string msg = upFiles.fileSaveAs(_upfile, _isthumbnail, _iswater, false, true);130             //返回成功信息131             context.Response.Write(msg);132             context.Response.End();133         }134         #endregion135 136         #region 编辑器上传处理===================================137         private void EditorFile(HttpContext context)138         {139             bool _iswater = false; //默认不打水印140             if (context.Request.QueryString["IsWater"] == "1")141                 _iswater = true;142             HttpPostedFile imgFile = context.Request.Files["imgFile"];143             if (imgFile == null)144             {145                 showError(context, "请选择要上传文件!");146                 return;147             }148             UpLoad upFiles = new UpLoad();149             string remsg = upFiles.fileSaveAs(imgFile, false, _iswater);150             //string pattern = @"^{\s*msg:\s*(.*)\s*,\s*msgbox:\s*https://www.gxlcms.com/\""(.*)https://www.gxlcms.com/\""\s*}$"; //键名前和键值前后都允许出现空白字符151             string pattern = @"^{\s*https://www.gxlcms.com/\""msghttps://www.gxlcms.com/\"":\s*https://www.gxlcms.com/\""(.*)https://www.gxlcms.com/\""\s*,\s*https://www.gxlcms.com/\""msgboxhttps://www.gxlcms.com/\"":\s*https://www.gxlcms.com/\""(.*)https://www.gxlcms.com/\""\s*}$"; //键名前和键值前后都允许出现空白字符152             Regex r = new Regex(pattern, RegexOptions.IgnoreCase); //正则表达式实例,不区分大小写153             Match m = r.Match(remsg); //搜索匹配项154             string msg = m.Groups[1].Value; //msg的值,正则表达式中第1个圆括号捕获的值155             string msgbox = m.Groups[2].Value; //msgbox的值,正则表达式中第2个圆括号捕获的值 156             if (msg == "0")157             {158                 showError(context, msgbox);159                 return;160             }161             Hashtable hash = new Hashtable();162             hash["error"] = 0;163             hash["url"] = msgbox;164             context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");165 166             string result = JsonMapper.ToJson(hash);167             //result = result.Replace("[","");168             //result = result.Replace("]", "");169             context.Response.Write(result);170             171            context.Response.End();172 173         }174         //显示错误175         private void showError(HttpContext context, string message)176         {177             Hashtable hash = new Hashtable();178             hash["error"] = 1;179             hash["message"] = message;180             context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");181             context.Response.Write(JsonMapper.ToJson(hash));182             context.Response.End();183         }184         #endregion185 186 187 188         #region Helper189         public class NameSorter : IComparer190         {191             public int Compare(object x, object y)192             {193                 if (x == null && y == null)194                 {195                     return 0;196                 }197                 if (x == null)198                 {199                     return -1;200                 }201                 if (y == null)202                 {203                     return 1;204                 }205                 FileInfo xInfo = new FileInfo(x.ToString());206                 FileInfo yInfo = new FileInfo(y.ToString());207 208                 return xInfo.FullName.CompareTo(yInfo.FullName);209             }210         }211 212         public class SizeSorter : IComparer213         {214             public int Compare(object x, object y)215             {216                 if (x == null && y == null)217                 {218                     return 0;219                 }220                 if (x == null)221                 {222                     return -1;223                 }224                 if (y == null)225                 {226                     return 1;227                 }228                 FileInfo xInfo = new FileInfo(x.ToString());229                 FileInfo yInfo = new FileInfo(y.ToString());230 231                 return xInfo.Length.CompareTo(yInfo.Length);232             }233         }234 235         public class TypeSorter : IComparer236         {237             public int Compare(object x, object y)238             {239                 if (x == null && y == null)240                 {241                     return 0;242                 }243                 if (x == null)244                 {245                     return -1;246                 }247                 if (y == null)248                 {249                     return 1;250                 }251                 FileInfo xInfo = new FileInfo(x.ToString());252                 FileInfo yInfo = new FileInfo(y.ToString());253 254                 return xInfo.Extension.CompareTo(yInfo.Extension);255             }256         }257 258         #endregion259 260         public bool IsReusable261         {262             get263             {264                 return false;265             }266         }267     }268 }

      1 using System;  2 using System.Collections;  3 using System.Collections.Generic;  4 using System.IO;  5 using System.Linq;  6 using System.Web;  7 using DotNet.Kernel.Common;  8   9 namespace BPMS.WEB 10 { 11     public class UpLoad 12     { 13         public UpLoad() 14         { 15  16         } 17         ///  18         /// 生成一个上传插件信息 19         ///  20         /// 上传控件id 21         /// 隐藏域id用来保存上传的图片路径 22         /// 初始化显示的图片地址 23         /// 上传成功之后用来显示上传图片的标签id 24         ///  25         public static string showUploadFile(string fileId, string hfId, string imgUrl, string listId) 26         { 27             string result = ""; 28             if (!string.IsNullOrEmpty(imgUrl)) 29             { 30                 result = "
    "; 31 } 32 else 33 { 34 result = "
    "; 35 } 36 37 return result; 38 } 39 #region 40 /// 41 /// 裁剪图片并保存 42 /// 43 public bool cropSaveAs(string fileName, string newFileName, int maxWidth, int maxHeight, int cropWidth, int cropHeight, int X, int Y) 44 { 45 string fileExt = Utils.GetFileExt(fileName); //文件扩展名,不含“.” 46 if (!IsImage(fileExt)) 47 { 48 return false; 49 } 50 string newFileDir = Utils.GetMapPath(newFileName.Substring(0, newFileName.LastIndexOf(@"/") + 1)); 51 //检查是否有该路径,没有则创建 52 if (!Directory.Exists(newFileDir)) 53 { 54 Directory.CreateDirectory(newFileDir); 55 } 56 try 57 { 58 string fileFullPath = Utils.GetMapPath(fileName); 59 string toFileFullPath = Utils.GetMapPath(newFileName); 60 return Thumbnail.MakeThumbnailImage(fileFullPath, toFileFullPath, 180, 180, cropWidth, cropHeight, X, Y); 61 } 62 catch 63 { 64 return false; 65 } 66 } 67 68 /// 69 /// 文件上传方法A 70 /// 71 /// 文件流 72 /// 是否生成缩略图 73 /// 是否打水印 74 /// 服务器文件路径 75 public string fileSaveAs(HttpPostedFile postedFile, bool isThumbnail, bool isWater) 76 { 77 return fileSaveAs(postedFile, isThumbnail, isWater, false, false); 78 } 79 80 /// 81 /// 文件上传方法B 82 /// 83 /// 文件流 84 /// 是否生成缩略图 85 /// 是否打水印 86 /// 是否必须上传图片 87 /// 服务器文件路径 88 public string fileSaveAs(HttpPostedFile postedFile, bool isThumbnail, bool isWater, bool _isImage) 89 { 90 return fileSaveAs(postedFile, isThumbnail, isWater, _isImage, false); 91 } 92 93 /// 94 /// 文件上传方法C 95 /// 96 /// 文件流 97 /// 是否生成缩略图 98 /// 是否打水印 99 /// 是否返回文件原名称100 /// 服务器文件路径101 public string fileSaveAs(HttpPostedFile postedFile, bool isThumbnail, bool isWater, bool _isImage, bool _isReOriginal)102 {103 try104 {105 string fileExt = Utils.GetFileExt(postedFile.FileName); //文件扩展名,不含“.”106 string originalFileName = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf(@"\") + 1); //取得文件原名107 string fileName = Utils.GetRamCode() + "." + fileExt; //随机文件名108 string dirPath = GetUpLoadPath(); //上传目录相对路径109 110 //检查文件扩展名是否合法111 if (!CheckFileExt(fileExt))112 {113 return "{\"msg\": \"0\", \"msgbox\": \"不允许上传" + fileExt + "类型的文件!\"}";114 }115 //检查是否必须上传图片116 if (_isImage && !IsImage(fileExt))117 {118 return "{\"msg\": \"0\", \"msgbox\": \"对不起,仅允许上传图片文件!\"}";119 }120 //检查文件大小是否合法121 if (!CheckFileSize(fileExt, postedFile.ContentLength))122 {123 return "{\"msg\": \"0\", \"msgbox\": \"文件超过限制的大小啦!\"}";124 }125 //获得要保存的文件路径126 string serverFileName = dirPath + fileName;127 string serverThumbnailFileName = dirPath + "small_" + fileName;128 string returnFileName = serverFileName;129 //物理完整路径 130 string toFileFullPath = Utils.GetMapPath(dirPath);131 //检查有该路径是否就创建132 if (!Directory.Exists(toFileFullPath))133 {134 Directory.CreateDirectory(toFileFullPath);135 }136 //保存文件137 postedFile.SaveAs(toFileFullPath + fileName);138 //如果是图片,检查图片尺寸是否超出限制139 if (IsImage(fileExt))140 {141 Thumbnail.MakeThumbnailImage(toFileFullPath + fileName, toFileFullPath + fileName, 3000, 3000);142 }143 //是否生成缩略图144 if (IsImage(fileExt) && isThumbnail)145 {146 Thumbnail.MakeThumbnailImage(toFileFullPath + fileName, toFileFullPath + "small_" + fileName, 150, 150, "R");147 // returnFileName += "," + serverThumbnailFileName; //返回缩略图,以逗号分隔开148 }149 //是否打图片水印150 if (IsWaterMark(fileExt) && isWater)151 {152 //switch (this.siteConfig.watermarktype)153 //{154 // case 1:155 // WaterMark.AddImageSignText(serverFileName, serverFileName,156 // this.siteConfig.watermarktext, this.siteConfig.watermarkposition,157 // this.siteConfig.watermarkimgquality, this.siteConfig.watermarkfont, this.siteConfig.watermarkfontsize);158 // break;159 // case 2:160 // WaterMark.AddImageSignPic(serverFileName, serverFileName,161 // this.siteConfig.watermarkpic, this.siteConfig.watermarkposition,162 // this.siteConfig.watermarkimgquality, this.siteConfig.watermarktransparency);163 // break;164 //}165 }166 //如果需要返回原文件名167 if (_isReOriginal)168 {169 return "{\"msg\": \"1\", \"msgbox\": https://www.gxlcms.com/\"" + serverFileName + "\", mstitle: https://www.gxlcms.com/\"" + originalFileName + "\"}";170 }171 return "{\"msg\": \"1\", \"msgbox\": https://www.gxlcms.com/\"" + returnFileName + "\"}";172 }173 catch174 {175 return "{\"msg\": \"0\", \"msgbox\": \"上传过程中发生意外错误!\"}";176 }177 }178 179 180 #region 私有方法181 182 /// 183 /// 返回上传目录相对路径184 /// 185 /// 上传文件名186 private string GetUpLoadPath()187 {188 //string path = "/Files/upload/"; //站点目录+上传目录189 string path = "/upload/"; //站点目录+上传目录190 path += DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd");191 return path + "/";192 }193 194 /// 195 /// 是否需要打水印196 /// 197 /// 文件扩展名,不含“.”198 private bool IsWaterMark(string _fileExt)199 {200 //判断是否开启水印201 if (1 == 1)202 {203 //判断是否可以打水印的图片类型204 ArrayList al = new ArrayList();205 al.Add("bmp");206 al.Add("jpeg");207 al.Add("jpg");208 al.Add("png");209 if (al.Contains(_fileExt.ToLower()))210 {211 return true;212 }213 }214 return false;215 }216 217 /// 218 /// 是否为图片文件219 /// 220 /// 文件扩展名,不含“.”221 private bool IsImage(string _fileExt)222 {223 ArrayList al = new ArrayList();224 al.Add("bmp");225 al.Add("jpeg");226 al.Add("jpg");227 al.Add("gif");228 al.Add("png");229 if (al.Contains(_fileExt.ToLower()))230 {231 return true;232 }233 return false;234 }235 236 /// 237 /// 检查是否为合法的上传文件238 /// 239 private bool CheckFileExt(string _fileExt)240 {241 //检查危险文件242 string[] excExt = { "asp", "aspx", "php", "jsp", "htm", "html" };243 for (int i = 0; i < excExt.Length; i++)244 {245 if (excExt[i].ToLower() == _fileExt.ToLower())246 {247 return false;248 }249 }250 //检查合法文件251 string[] allowExt = { "gif", "jpg", "png", "bmp", "rar", "zip", "doc", "xls", "txt" };252 for (int i = 0; i < allowExt.Length; i++)253 {254 if (allowExt[i].ToLower() == _fileExt.ToLower())255 {256 return true;257 }258 }259 return false;260 }261 262 /// 263 /// 检查文件大小是否合法264 /// 265 /// 文件扩展名,不含“.”266 /// 文件大小(KB)267 private bool CheckFileSize(string _fileExt, int _fileSize)268 {269 //判断是否为图片文件270 if (IsImage(_fileExt))271 {272 if (_fileSize > 10000 * 10240)273 {274 return false;275 }276 }277 else278 {279 if (_fileSize > 10000 * 10240)280 {281 return false;282 }283 }284 return true;285 }286 287 #endregion288 289 #endregion290 }291 }

    人气教程排行