插件webuploader实现文件上传

xiaoxiao2021-02-28  119

使用插件webuploader来实现文件的上传功能,文件下载地址:webuploader上传插件 引用:

<script type="text/javascript" src="../script/webuploader/webuploader.min.js"></script> <script type="text/javascript" charset="utf-8" src="../script/uploader.js"></script><!--参见最下方-->

前台代码:

<div class="div-content"> <div class="list"> <dl> <dt>文件:</dt> <dd> <asp:TextBox ID="txtImgUrl" runat="server" CssClass="input normal upload-path" /> <div class="upload-box upload-img"> </div> </dd> </dl> </div> <div class="toolbar"> <asp:Button ID="btnOK" Style="margin-left: 20px" runat="server" Text="上传" class="btn" OnClick="btnOK_Click" /> </div> </div> <script type="text/javascript"> $(function () { //初始化上传控件 $(".upload-img").InitUploader({ sendurl: "../tool/upload_ajax.ashx", swf: "../script/webuploader/uploader.swf" }); }); </script>

一般处理程序 upload_ajax.ashx 如下:

public class upload_ajax : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { //取得处事类型 string action =LabRequest.GetQueryString("action"); switch (action) { default: //普通上传 UpLoadFile(context); break; } } #region 上传文件处理=================================== private void UpLoadFile(HttpContext context) { string _delfile = LabRequest.GetString("DelFilePath"); HttpPostedFile _upfile = context.Request.Files["Filedata"]; bool _iswater = false; //默认不打水印 bool _isthumbnail = false; //默认不生成缩略图 if (LabRequest.GetQueryString("IsWater") == "1") _iswater = true; if (LabRequest.GetQueryString("IsThumbnail") == "1") _isthumbnail = true; if (_upfile == null) { context.Response.Write("{\"status\": 0, \"msg\": \"请选择要上传文件!\"}"); return; } UpLoad upFiles = new UpLoad(); string msg = upFiles.fileSaveAs(_upfile, _isthumbnail, _iswater); //删除已存在的旧文件,旧文件不为空且应是上传文件,防止跨目录删除 if (!string.IsNullOrEmpty(_delfile) && _delfile.IndexOf("../") == -1 && _delfile.ToLower().StartsWith("/uploadfile")) { Utils.DeleteUpFile(_delfile); } //返回成功信息 context.Response.Write(msg); context.Response.End(); } #endregion #region Helper public class NameSorter : IComparer { public int Compare(object x, object y) { if (x == null && y == null) { return 0; } if (x == null) { return -1; } if (y == null) { return 1; } FileInfo xInfo = new FileInfo(x.ToString()); FileInfo yInfo = new FileInfo(y.ToString()); return xInfo.FullName.CompareTo(yInfo.FullName); } } public class SizeSorter : IComparer { public int Compare(object x, object y) { if (x == null && y == null) { return 0; } if (x == null) { return -1; } if (y == null) { return 1; } FileInfo xInfo = new FileInfo(x.ToString()); FileInfo yInfo = new FileInfo(y.ToString()); return xInfo.Length.CompareTo(yInfo.Length); } } public class TypeSorter : IComparer { public int Compare(object x, object y) { if (x == null && y == null) { return 0; } if (x == null) { return -1; } if (y == null) { return 1; } FileInfo xInfo = new FileInfo(x.ToString()); FileInfo yInfo = new FileInfo(y.ToString()); return xInfo.Extension.CompareTo(yInfo.Extension); } } #endregion public bool IsReusable { get { return false; } } }

类 UpLoad.cs 如下:

public class UpLoad { private siteconfig siteConfig; public UpLoad() { siteConfig = new OABLL.siteconfig().loadConfig(); } /// <summary> /// 文件上传方法 /// </summary> /// <param name="postedFile">文件流</param> /// <param name="isThumbnail">是否生成缩略图</param> /// <param name="isWater">是否打水印</param> /// <returns>上传后文件信息</returns> public string fileSaveAs(HttpPostedFile postedFile, bool isThumbnail, bool isWater) { try { string fileExt = FileHelper.GetExtension(postedFile.FileName).Substring(1); //文件扩展名,不含“.” int fileSize = postedFile.ContentLength; //获得文件大小,以字节为单位 string fileName = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf(@"\") + 1); //取得原文件名 string newFileName = RandomHelper.GetRamCode() + "." + fileExt; //随机生成新的文件名 //string newThumbnailFileName = "thumb_" + newFileName; //随机生成缩略图文件名 string path = ""; if (DateTime.Now.Month >= 10) { path = DateTime.Now.Year.ToString() + DateTime.Now.Month; } else { path = DateTime.Now.Year + "0" + DateTime.Now.Month; } string upLoadPath = "/uploadfile/" + path + "/"; //上传目录相对路径 string fullUpLoadPath = FileHelper.GetMapPath(upLoadPath); //上传目录的物理路径 string newFilePath = upLoadPath + newFileName; //上传后的路径 string upLoadThumbnail300Path = "/Img300/" + path + "/"; //上传目录相对路径 string fullUpLoadThumbnail300Path = FileHelper.GetMapPath(upLoadThumbnail300Path); //上传目录的物理路径 string newThumbnail300Path = upLoadThumbnail300Path + newFileName; //上传后的缩略图路径 string upLoadThumbnailMidPath = "/MidImg/" + path + "/"; //上传目录相对路径 string fullUpLoadThumbnailMidPath = FileHelper.GetMapPath(upLoadThumbnailMidPath); //上传目录的物理路径 string newThumbnailMidPath = upLoadThumbnailMidPath + newFileName; //上传后的缩略图路径 string upLoadThumbnailSmallPath = "/SmallImg/" + path + "/"; //上传目录相对路径 string fullUpLoadThumbnailSmallPath = FileHelper.GetMapPath(upLoadThumbnailSmallPath); //上传目录的物理路径 string newThumbnailSmallPath = upLoadThumbnailSmallPath + newFileName; //上传后的缩略图路径 //检查文件扩展名是否合法 if (!CheckFileExt(fileExt)) { return "{\"status\": 0, \"msg\": \"不允许上传" + fileExt + "类型的文件!\"}"; } //检查文件大小是否合法 if (!CheckFileSize(fileExt, fileSize)) { return "{\"status\": 0, \"msg\": \"文件超过限制的大小!\"}"; } //检查上传的物理路径是否存在,不存在则创建 if (!Directory.Exists(fullUpLoadPath)) { Directory.CreateDirectory(fullUpLoadPath); } if (!Directory.Exists(fullUpLoadThumbnail300Path)) { Directory.CreateDirectory(fullUpLoadThumbnail300Path); } if (!Directory.Exists(fullUpLoadThumbnailMidPath)) { Directory.CreateDirectory(fullUpLoadThumbnailMidPath); } if (!Directory.Exists(fullUpLoadThumbnailSmallPath)) { Directory.CreateDirectory(fullUpLoadThumbnailSmallPath); } //保存文件 postedFile.SaveAs(fullUpLoadPath + newFileName); //如果是图片,检查是否需要生成缩略图,是则生成 if (IsImage(fileExt) && isThumbnail) { postedFile.SaveAs(fullUpLoadThumbnail300Path + newFileName); postedFile.SaveAs(fullUpLoadThumbnailMidPath + newFileName); postedFile.SaveAs(fullUpLoadThumbnailSmallPath + newFileName); Thumbnail.MakeThumbnailImage(fullUpLoadPath + newFileName, fullUpLoadThumbnail300Path + newFileName, 300, 300, "HW"); Thumbnail.MakeThumbnailImage(fullUpLoadPath + newFileName, fullUpLoadThumbnailMidPath + newFileName, 150, 150, "HW"); Thumbnail.MakeThumbnailImage(fullUpLoadPath + newFileName, fullUpLoadThumbnailSmallPath + newFileName, 50, 50, "HW"); } else { newThumbnail300Path = newFilePath; //不生成缩略图则返回原图 } //如果是图片,检查是否需要打水印 if (IsWaterMark(fileExt) && isWater) { switch (this.siteConfig.watermarktype) { case 1: WaterMark.AddImageSignText(newFilePath, newFilePath, this.siteConfig.watermarktext, this.siteConfig.watermarkposition, this.siteConfig.watermarkimgquality, this.siteConfig.watermarkfont, this.siteConfig.watermarkfontsize); WaterMark.AddImageSignText(newThumbnail300Path, newThumbnail300Path, this.siteConfig.watermarktext, this.siteConfig.watermarkposition, this.siteConfig.watermarkimgquality, this.siteConfig.watermarkfont, this.siteConfig.watermarkfontsize); break; case 2: WaterMark.AddImageSignPic(newFilePath, newFilePath, this.siteConfig.watermarkpic, this.siteConfig.watermarkposition, this.siteConfig.watermarkimgquality, this.siteConfig.watermarktransparency); WaterMark.AddImageSignPic(newThumbnail300Path, newThumbnail300Path, this.siteConfig.watermarkpic, this.siteConfig.watermarkposition, this.siteConfig.watermarkimgquality, this.siteConfig.watermarktransparency); break; } } //处理完毕,返回JOSN格式的文件信息 return "{\"status\": 1, \"msg\": \"上传文件成功!\", \"name\": \"" + fileName + "\", \"path\": \"" + newFilePath + "\", \"thumb\": \"" + newThumbnail300Path + "\", \"size\": " + fileSize + ", \"ext\": \"" + fileExt + "\"}"; } catch { return "{\"status\": 0, \"msg\": \"上传过程中发生意外错误!\"}"; } } /// <summary> /// 保存远程文件到本地 /// </summary> /// <param name="fileUri">URI地址</param> /// <returns>上传后的路径</returns> public string remoteSaveAs(string fileUri) { WebClient client = new WebClient(); string fileExt = string.Empty; //文件扩展名,不含“.” if (fileUri.LastIndexOf(".") == -1) { fileExt = "gif"; } else { fileExt = Utils.GetFileExt(fileUri); } string newFileName = Utils.GetRamCode() + "." + fileExt; //随机生成新的文件名 string upLoadPath = GetUpLoadPath(); //上传目录相对路径 string fullUpLoadPath = Utils.GetMapPath(upLoadPath); //上传目录的物理路径 string newFilePath = upLoadPath + newFileName; //上传后的路径 //检查上传的物理路径是否存在,不存在则创建 if (!Directory.Exists(fullUpLoadPath)) { Directory.CreateDirectory(fullUpLoadPath); } try { client.DownloadFile(fileUri, fullUpLoadPath + newFileName); //如果是图片,检查是否需要打水印 if (IsWaterMark(fileExt)) { switch (this.siteConfig.watermarktype) { case 1: WaterMark.AddImageSignText(newFilePath, newFilePath, this.siteConfig.watermarktext, this.siteConfig.watermarkposition, this.siteConfig.watermarkimgquality, this.siteConfig.watermarkfont, this.siteConfig.watermarkfontsize); break; case 2: WaterMark.AddImageSignPic(newFilePath, newFilePath, this.siteConfig.watermarkpic, this.siteConfig.watermarkposition, this.siteConfig.watermarkimgquality, this.siteConfig.watermarktransparency); break; } } } catch { return string.Empty; } client.Dispose(); return newFilePath; } #region 私有方法 /// <summary> /// 返回上传目录相对路径 /// </summary> /// <param name="fileName">上传文件名</param> private string GetUpLoadPath() { string path = siteConfig.webpath + siteConfig.filepath + "/"; //站点目录+上传目录 switch (this.siteConfig.filesave) { case 1: //按年月日每天一个文件夹 path += DateTime.Now.ToString("yyyyMMdd"); break; default: //按年月/日存入不同的文件夹 path += DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd"); break; } return path + "/"; } /// <summary> /// 是否需要打水印 /// </summary> /// <param name="_fileExt">文件扩展名,不含“.”</param> private bool IsWaterMark(string _fileExt) { //判断是否开启水印 if (this.siteConfig.watermarktype > 0) { //判断是否可以打水印的图片类型 ArrayList al = new ArrayList(); al.Add("bmp"); al.Add("jpeg"); al.Add("jpg"); al.Add("png"); if (al.Contains(_fileExt.ToLower())) { return true; } } return false; } /// <summary> /// 是否为图片文件 /// </summary> /// <param name="_fileExt">文件扩展名,不含“.”</param> private bool IsImage(string _fileExt) { ArrayList al = new ArrayList(); al.Add("bmp"); al.Add("jpeg"); al.Add("jpg"); al.Add("gif"); al.Add("png"); if (al.Contains(_fileExt.ToLower())) { return true; } return false; } /// <summary> /// 检查是否为合法的上传文件 /// </summary> private bool CheckFileExt(string _fileExt) { //检查危险文件 string[] excExt = { "asp", "aspx", "ashx", "asa", "asmx", "asax", "php", "jsp", "htm", "html" }; for (int i = 0; i < excExt.Length; i++) { if (excExt[i].ToLower() == _fileExt.ToLower()) { return false; } } //检查合法文件 string[] allowExt = (this.siteConfig.fileextension + "," + this.siteConfig.videoextension).Split(','); for (int i = 0; i < allowExt.Length; i++) { if (allowExt[i].ToLower() == _fileExt.ToLower()) { return true; } } return false; } /// <summary> /// 检查文件大小是否合法 /// </summary> /// <param name="_fileExt">文件扩展名,不含“.”</param> /// <param name="_fileSize">文件大小(B)</param> private bool CheckFileSize(string _fileExt, int _fileSize) { //将视频扩展名转换成ArrayList ArrayList lsVideoExt = new ArrayList(this.siteConfig.videoextension.ToLower().Split(',')); //判断是否为图片文件 if (IsImage(_fileExt)) { if (this.siteConfig.imgsize > 0 && _fileSize > this.siteConfig.imgsize * 1024) { return false; } } else if (lsVideoExt.Contains(_fileExt.ToLower())) { if (this.siteConfig.videosize > 0 && _fileSize > this.siteConfig.videosize * 1024) { return false; } } else { if (this.siteConfig.attachsize > 0 && _fileSize > this.siteConfig.attachsize * 1024) { return false; } } return true; } #endregion }

另外 upload.js 如下:

$(function () { //初始化绑定默认的属性 $.upLoadDefaults = $.upLoadDefaults || {}; $.upLoadDefaults.property = { multiple: false, //是否多文件 water: false, //是否加水印 thumbnail: false, //是否生成缩略图 sendurl: null, //发送地址 filetypes: "gif,jpg,png,bmp,rar,zip,doc,xls,txt,docx", //文件类型 filesize: "10240", //文件大小 btntext: "浏览...", //上传按钮的文字 swf: null //SWF上传控件相对地址 }; //初始化上传控件 $.fn.InitUploader = function (b) { var fun = function (parentObj) { var p = $.extend({}, $.upLoadDefaults.property, b || {}); var btnObj = $('<div class="upload-btn">' + p.btntext + '</div>').appendTo(parentObj); //初始化属性 p.sendurl += "?action=UpLoadFile"; if (p.water) { p.sendurl += "&IsWater=1"; } if (p.thumbnail) { p.sendurl += "&IsThumbnail=1"; } if (!p.multiple) { p.sendurl += "&DelFilePath=" + parentObj.siblings(".upload-path").val(); } //初始化WebUploader var uploader = WebUploader.create({ compress: false, //不压缩 auto: true, //自动上传 swf: p.swf, //SWF路径 server: p.sendurl, //上传地址 pick: { id: btnObj, multiple: p.multiple }, accept: { /*title: 'Images',*/ extensions: p.filetypes /*mimeTypes: 'image/*'*/ }, formData: { 'DelFilePath': '' //定义参数 }, fileVal: 'Filedata', //上传域的名称 fileSingleSizeLimit: p.filesize * 1024 //文件大小 }); //当validate不通过时,会以派送错误事件的形式通知 uploader.on('error', function (type) { switch (type) { case 'Q_EXCEED_NUM_LIMIT': alert("错误:上传文件数量过多!"); break; case 'Q_EXCEED_SIZE_LIMIT': alert("错误:文件总大小超出限制!"); break; case 'F_EXCEED_SIZE': alert("错误:文件大小超出限制!"); break; case 'Q_TYPE_DENIED': alert("错误:禁止上传该类型文件!"); break; case 'F_DUPLICATE': alert("错误:请勿重复上传该文件!"); break; default: alert('错误代码:' + type); break; } }); //当有文件添加进来的时候 uploader.on('fileQueued', function (file) { //如果是单文件上传,把旧的文件地址传过去 if (!p.multiple) { uploader.options.formData.DelFilePath = parentObj.siblings(".upload-path").val(); } //防止重复创建 if (parentObj.children(".upload-progress").length == 0) { //创建进度条 var fileProgressObj = $('<div class="upload-progress"></div>').appendTo(parentObj); var progressText = $('<span class="txt">正在上传,请稍候...</span>').appendTo(fileProgressObj); var progressBar = $('<span class="bar"><b></b></span>').appendTo(fileProgressObj); var progressCancel = $('<a class="close" title="取消上传">关闭</a>').appendTo(fileProgressObj); //绑定点击事件 progressCancel.click(function () { uploader.cancelFile(file); fileProgressObj.remove(); }); } }); //文件上传过程中创建进度条实时显示 uploader.on('uploadProgress', function (file, percentage) { var progressObj = parentObj.children(".upload-progress"); progressObj.children(".txt").html(file.name); progressObj.find(".bar b").width(percentage * 100 + "%"); }); //当文件上传出错时触发 uploader.on('uploadError', function (file, reason) { uploader.removeFile(file); //从队列中移除 alert(file.name + "上传失败,错误代码:" + reason); }); //当文件上传成功时触发 uploader.on('uploadSuccess', function (file, data) { if (data.status == '0') { var progressObj = parentObj.children(".upload-progress"); progressObj.children(".txt").html(data.msg); } if (data.status == '1') { //如果是单文件上传,则赋值相应的表单 if (!p.multiple) { parentObj.siblings(".upload-name").val(data.name); parentObj.siblings(".upload-path").val(data.path); parentObj.siblings(".upload-size").val(data.size); } else { addImage(parentObj, data.path, data.thumb); } var progressObj = parentObj.children(".upload-progress"); progressObj.children(".txt").html("上传成功:" + file.name); } uploader.removeFile(file); //从队列中移除 }); //不管成功或者失败,文件上传完成时触发 uploader.on('uploadComplete', function (file) { var progressObj = parentObj.children(".upload-progress"); progressObj.children(".txt").html("上传完成"); //如果队列为空,则移除进度条 if (uploader.getStats().queueNum == 0) { progressObj.remove(); } }); }; return $(this).each(function () { fun($(this)); }); } });
转载请注明原文地址: https://www.6miu.com/read-68800.html

最新回复(0)