现在网站不再讲究的是功能性,更多的是用户体验性,在这里上传图片就需要用到ajax无刷新上传图片,这里面包含的东西不是一点半点 。这里用到的是一个插件swfupload 实现无刷新上传图片
在做项目时,需要用到一个图片的无刷新上传,之前听说过SWFUpload,于是想要通过SWFUpload来进行图片的无刷新上传,由于我的项目属于是ASP.NET项目,所以本文着重讲解ASP.NET 的使用,个人感觉示例基本给的很清晰,参考文档进行开发,并非难事
0. 首先下载swfUpload 包,在下载的包中有samples文件夹,samples下有demos文件夹,打开demos文件夹可看到如下图所示结构
我们待会会用到的包括,swfupload目录下的文件,css不建议使用以避免与自己写的CSS相冲突使得页面布局完全乱掉,如果要添加样式最好自己写
打开 applicationdemo.net目录会看到这样的结构
打开index.html可以看到这样的页面
点击NET2.0下的Application Demo C#项
添加资源引用
将要引用的资源包含到项目中(包括swfupload文件夹下的文件与,demo下的资源文件,handlers.js是在demo中js目录下的js文件)
首先熟悉demo,将demo中的页面包含到项目中
在Defaut.aspx页面中使用swfUpload组件进行图片的无刷新上传直接运行,看效果,大概了解基本过程
修改handlers.js文件
我的项目文件结构大概是这样的
我的处理文件上传的页面是ImageUploadHandler.ashx,获取缩略图的页面是GetThumbHandler.ashx,Thumbnail.cs是demo中App_Code文件夹中的文件,个人觉得像这种只处理逻辑功能而不展现页面的最好都用一般处理程序来实现。由于哪个文件处理上传哪个文件生成缩略图已经在handlers.js文件中写死了,所以必须要修改handlers.js文件以能够使页面正常运行
最终修改版汇总
Thumbnail
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 /// <summary> /// 缩略图 /// </summary> public class Thumbnail { public Thumbnail(string id, byte[] data) { this.ID = id; this.Data = data; } private string id; /// <summary> /// 图片id /// </summary> public string ID { get { return this.id; } set { this.id = value; } } private byte[] thumbnail_data; /// <summary> /// 图片的二进制数据 /// </summary> public byte[] Data { get { return this.thumbnail_data; } set { this.thumbnail_data = value; } } private string contentType; /// <summary> /// 图片对应的MIME类型 /// </summary> public string ContentType { get { return contentType; } set { contentType = value; } } }Html Demo
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Upload Images</title> <script src=http://www.shancun.net/skin/default/image/nopic.gif <script src=http://www.shancun.net/skin/default/image/nopic.gif <script> //注:div的id名称最好不要改,要改的话在handlers.js文件中也要进行修改,div的名称已经在handlers.js文件中写死 var swfu; window.onload = function () { swfu = new SWFUpload({ // 后台设置,设置处理上传的页面 upload_url: "/Handlers/ImageUploadHandler.ashx", // 文件上传大小限制设置 file_size_limit: "3 MB", //文件类型设置,多种格式以英文中的分号分开 file_types: "*.jpg;*.png", //文件描述,与弹出的选择文件对话框相关 file_types_description : "Images file", //设置上传文件数量限制 file_upload_limit: "1", //事件处理程序,最好不要改,事件处理程序已在handlers.js文件中定义 // Event Handler Settings - these functions as defined in Handlers.js // The handlers are not part of SWFUpload but are part of my website and control how // my website reacts to the SWFUpload events. file_queue_error_handler : fileQueueError, file_dialog_complete_handler : fileDialogComplete, upload_progress_handler : uploadProgress, upload_error_handler : uploadError, upload_success_handler : uploadSuccess, upload_complete_handler : uploadComplete, // 上传按钮设置 button_image_url : "/swfupload/images/XPButtonNoText_160x22.png", button_placeholder_id: "spanButtonPlaceholder", button_width: 160, button_height: 22, button_text : '请选择图片 (最大3M)', button_text_style : '.button { font-family: Helvetica, Arial, sans-serif; font-size: 14pt; } .buttonSmall { font-size: 10pt; }', button_text_top_padding: 1, button_text_left_padding: 5, // swfupload.swf flash设置 flash_url : "/swfupload/swfupload.swf", //自定义的其他设置 custom_settings : { upload_target: "divFileProgressContainer" }, // 是否开启调试模式,调试时可以设置为true,发布时设置为false debug: false }); } </script> </head> <body> <form id="form1"> <div id="content"> <h2>Upload Images Demo</h2> <div id="swfu_container" style="margin: 0px 10px;"> <div> <span id="spanButtonPlaceholder"></span> </div> <div id="divFileProgressContainer" style="height: 75px;"></div> <div id="thumbnails"></div> </div> </div> </form> </body> </html>ImageUploadHandler
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 /// <summary> /// 图片上传处理 /// </summary> public class ImageUploadHandler : IHttpHandler, IRequiresSessionState { /// <summary> /// 记录日志 logger /// </summary> private static Common.LogHelper logger = new Common.LogHelper(typeof(ImageUploadHandler)); public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; System.Drawing.Image thumbnail_image = null; System.Drawing.Image original_image = null; System.Drawing.Bitmap final_image = null; System.Drawing.Graphics graphic = null; MemoryStream ms = null; try { //验证用户是否登录,是否有权限上传 if (context.Session["User"]==null) { context.Response.Write("没有上传图片的权限!"); context.Response.End(); return; } //获取上传文件 HttpPostedFile image_upload = context.Request.Files["Filedata"]; //获取文件扩展名 string fileExt = System.IO.Path.GetExtension(image_upload.FileName).ToLower(); //验证文件扩展名是否符合要求,是否是允许的图片格式 if (fileExt!=".jpg"&&fileExt!=".png") { return; } //当前时间字符串 string timeString = DateTime.Now.ToString("yyyyMMddHHmmssfff"); //图片保存虚拟路径构建 string path = "/Upload/"+timeString + fileExt; //保存到Session 变量中 context.Session["imgPath"] = path; //获取、构建要上传文件的物理路径 string serverPath = context.Server.MapPath("~/"+path); //保存图片到服务器 image_upload.SaveAs(serverPath); //记录日志 logger.Debug("图片上传成功!"); #region 生成缩略图 // 获取上传图片的文件流 original_image = System.Drawing.Image.FromStream(image_upload.InputStream); // 根据原图计算缩略图的宽度和高度,及缩放比例等~~ int width = original_image.Width; int height = original_image.Height; int target_width = 100; int target_height = 100; int new_width, new_height; float target_ratio = (float)target_width / (float)target_height; float image_ratio = (float)width / (float)height; if (target_ratio > image_ratio) { new_height = target_height; new_width = (int)Math.Floor(image_ratio * (float)target_height); } else { new_height = (int)Math.Floor((float)target_width / image_ratio); new_width = target_width; } new_width = new_width > target_width ? target_width : new_width; new_height = new_height > target_height ? target_height : new_height; //创建缩略图 final_image = new System.Drawing.Bitmap(target_width, target_height); graphic = System.Drawing.Graphics.FromImage(final_image); graphic.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Black), new System.Drawing.Rectangle(0, 0, target_width, target_height)); int paste_x = (target_width - new_width) / 2; int paste_y = (target_height - new_height) / 2; graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; //graphic.DrawImage(thumbnail_image, paste_x, paste_y, new_width, new_height); graphic.DrawImage(original_image, paste_x, paste_y, new_width, new_height); // Store the thumbnail in the session (Note: this is bad, it will take a lot of memory, but this is just a demo) ms = new MemoryStream(); //将缩略图保存到内存流中 final_image.Save(ms, System.Drawing.Imaging.ImageFormat.Png); #endregion //建立 Thumbnail对象 Thumbnail thumb = new Thumbnail(timeString, ms.GetBuffer()); //保存缩略图到Session 中,也可以保存成文件,保存为图片 context.Session["file_info"] = thumb; //操作成功,返回HTTP状态码设置为 200 context.Response.StatusCode = 200; //输出缩略图的id,在生成缩略图时要用到 context.Response.Write(thumb.ID); } catch(Exception ex) { // 出现异常,返回 500,服务器内部错误 context.Response.StatusCode = 500; //记录错误日志 logger.Error(ex); } finally { // 释放资源 if (final_image != null) final_image.Dispose(); if (graphic != null) graphic.Dispose(); if (original_image != null) original_image.Dispose(); if (thumbnail_image != null) thumbnail_image.Dispose(); if (ms != null) ms.Close(); context.Response.End(); } } public bool IsReusable { get { return false; } } }GetThumbHandler
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 /// <summary> /// 获取缩略图 /// </summary> public class GetThumbHandler : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //获取缩略图id string id = context.Request.QueryString["id"]; //id为空则返回错误 if (String.IsNullOrEmpty(id)) { context.Response.StatusCode = 404; context.Response.Write("Not Found"); context.Response.End(); return; } //从Session中获取缩略图文件 Thumbnail thumb= context.Session["file_info"] as Thumbnail; //判断id是否一致 if (thumb.ID == id) { //重新设置响应MIME 类型 context.Response.ContentType = "image/png"; //输出二进制流信息 context.Response.BinaryWrite(thumb.Data); //截止输出 context.Response.End(); return; } //没有找到相应图片,返回404 context.Response.StatusCode = 404; context.Response.Write("Not Found"); context.Response.End(); } public bool IsReusable { get { return false; } } }handlers.js 文件
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 function fileQueueError(file, errorCode, message) { try { var imageName = "error.gif"; var errorName = ""; if (errorCode == SWFUpload.errorCode_QUEUE_LIMIT_EXCEEDED) { errorName = "上传文件过多!"; } if (errorName != "") { alert(errorName); return; } switch (errorCode) { case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: imageName = "zerobyte.gif"; break; case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT: imageName = "toobig.gif"; break; case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE: default: alert(message); break; } //添加图片,注意路径 addImage("/swfupload/images/" + imageName); } catch (ex) { this.debug(ex); } } function fileDialogComplete(numFilesSelected, numFilesQueued) { try { if (numFilesQueued > 0) { this.startUpload(); } } catch (ex) { this.debug(ex); } } function uploadProgress(file, bytesLoaded) { try { var percent = Math.ceil((bytesLoaded / file.size) * 100); var progress = new FileProgress(file, this.customSettings.upload_target); progress.setProgress(percent); if (percent === 100) { progress.setStatus("正在创建缩略图..."); progress.toggleCancel(false, this); } else { progress.setStatus("正在上传..."); progress.toggleCancel(true, this); } } catch (ex) { this.debug(ex); } } function uploadSuccess(file, serverData) { try { //添加缩略图~~~ //修改这里来设置生成缩略图的页面 addImage("/Handlers/GetThumbHandler.ashx?id=" + serverData); var progress = new FileProgress(file, this.customSettings.upload_target); progress.setStatus("缩略图创建成功!"); progress.toggleCancel(false); } catch (ex) { this.debug(ex); } } function uploadComplete(file) { try { if (this.getStats().files_queued > 0) { this.startUpload(); } else { var progress = new FileProgress(file, this.customSettings.upload_target); progress.setComplete(); progress.setStatus("图片上传成功"); progress.toggleCancel(false); } } catch (ex) { this.debug(ex); } } function uploadError(file, errorCode, message) { var imageName = "error.gif"; var progress; try { switch (errorCode) { case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED: try { progress = new FileProgress(file, this.customSettings.upload_target); progress.setCancelled(); progress.setStatus("上传操作被取消"); progress.toggleCancel(false); } catch (ex1) { this.debug(ex1); } break; case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED: try { progress = new FileProgress(file, this.customSettings.upload_target); progress.setCancelled(); progress.setStatus("上传停止!"); progress.toggleCancel(true); } catch (ex2) { this.debug(ex2); } case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED: imageName = "uploadlimit.gif"; break; default: alert(message); break; } addImage("/swfupload/images/" + imageName); } catch (ex3) { this.debug(ex3); } } function addImage(src) { var newImg = document.createElement("img"); newImg.style.margin = "5px"; document.getElementById("thumbnails").appendChild(newImg); if (newImg.filters) { try { newImg.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 0; } catch (e) { // If it is not set initially, the browser will throw an error. This will set it if it is not set yet. newImg.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + 0 + ')'; } } else { newImg.style.opacity = 0; } newImg.onload = function () { fadeIn(newImg, 0); }; newImg.src = src; } function fadeIn(element, opacity) { var reduceOpacityBy = 5; var rate = 30; // 15 fps if (opacity < 100) { opacity += reduceOpacityBy; if (opacity > 100) { opacity = 100; } if (element.filters) { try { element.filters.item("DXImageTransform.Microsoft.Alpha").opacity = opacity; } catch (e) { // If it is not set initially, the browser will throw an error. This will set it if it is not set yet. element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')'; } } else { element.style.opacity = opacity / 100; } } if (opacity < 100) { setTimeout(function () { fadeIn(element, opacity); }, rate); } } function FileProgress(file, targetID) { this.fileProgressID = "divFileProgress"; this.fileProgressWrapper = document.getElementById(this.fileProgressID); if (!this.fileProgressWrapper) { this.fileProgressWrapper = document.createElement("div"); this.fileProgressWrapper.className = "progressWrapper"; this.fileProgressWrapper.id = this.fileProgressID; this.fileProgressElement = document.createElement("div"); this.fileProgressElement.className = "progressContainer"; var progressCancel = document.createElement("a"); progressCancel.className = "progressCancel"; progressCancel.href = "#"; progressCancel.style.visibility = "hidden"; progressCancel.appendChild(document.createTextNode(" ")); var progressText = document.createElement("div"); progressText.className = "progressName"; progressText.appendChild(document.createTextNode(file.name)); var progressBar = document.createElement("div"); progressBar.className = "progressBarInProgress"; var progressStatus = document.createElement("div"); progressStatus.className = "progressBarStatus"; progressStatus.innerHTML = " "; this.fileProgressElement.appendChild(progressCancel); this.fileProgressElement.appendChild(progressText); this.fileProgressElement.appendChild(progressStatus); this.fileProgressElement.appendChild(progressBar); this.fileProgressWrapper.appendChild(this.fileProgressElement); document.getElementById(targetID).appendChild(this.fileProgressWrapper); fadeIn(this.fileProgressWrapper, 0); } else { this.fileProgressElement = this.fileProgressWrapper.firstChild; this.fileProgressElement.childNodes[1].firstChild.nodevalue = file.name; } this.height = this.fileProgressWrapper.offsetHeight; } FileProgress.prototype.setProgress = function (percentage) { this.fileProgressElement.className = "progressContainer green"; this.fileProgressElement.childNodes[3].className = "progressBarInProgress"; this.fileProgressElement.childNodes[3].style.width = percentage + "%"; }; FileProgress.prototype.setComplete = function () { this.fileProgressElement.className = "progressContainer blue"; this.fileProgressElement.childNodes[3].className = "progressBarComplete"; this.fileProgressElement.childNodes[3].style.width = ""; }; FileProgress.prototype.setError = function () { this.fileProgressElement.className = "progressContainer red"; this.fileProgressElement.childNodes[3].className = "progressBarError"; this.fileProgressElement.childNodes[3].style.width = ""; }; FileProgress.prototype.setCancelled = function () { this.fileProgressElement.className = "progressContainer"; this.fileProgressElement.childNodes[3].className = "progressBarError"; this.fileProgressElement.childNodes[3].style.width = ""; }; FileProgress.prototype.setStatus = function (status) { this.fileProgressElement.childNodes[2].innerHTML = status; }; FileProgress.prototype.toggleCancel = function (show, swfuploadInstance) { this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden"; if (swfuploadInstance) { var fileID = this.fileProgressID; this.fileProgressElement.childNodes[0].onclick = function () { swfuploadInstance.cancelUpload(fileID); return false; }; } };以上所述就是本文的全部内容了,希望对大家学习asp.net能够有所帮助。