使用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
/// <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
<!doctype html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>upload images</title> <script src="swfupload/swfupload.js"></script> <script src="swfupload/handlers.js"></script> <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
/// <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; /* new way */ //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
/// <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 文件
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 { /* i want the next upload to continue automatically so i'll call startupload here */ 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); } } /* ****************************************** * fileprogress object * control object for displaying file info * ****************************************** */ 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能够有所帮助。