网站编辑文章的时候须要插入图片、文件。若是使用FileUpload控件必须提交表单致使页面刷新,而因为AJAX不容许上传文件,因此必须使用其余解决方案。Flash提供了异步上传文件的功能,这里简介一下别人写好的flash控件:SWFUpload。javascript
本身整理的swfupload开发包http://pan.baidu.com/s/1f3IREcss
下面开始咱们的图片上传旅程前端
swfupload上传图片文件:java
前台代码:react
<%--jquery-ui使用到的样式--%> <link href="/Css/base/jquery-ui.css" rel="stylesheet" /> <%--项目中使用到了jquery,因此需引入jquery--%> <script src="/Scripts/jquery-1.8.2.min.js"></script> <%--后面头像截取使用到了jquery-ui,因此这里一并引入到项目中--%> <script src="/Scripts/jquery-ui-1.8.24.min.js"></script> <%--下面是使用swfupload须要的一些文件,须要一并引入到项目中--%> <link href="/lib/swfupload/css/default.css" rel="stylesheet" /> <script src="/lib/swfupload/swfupload.js"></script> <script src="/lib/swfupload/handlers.js"></script> <script type="text/javascript"> var filename; var swfu;
window.onload = function () { swfu = new SWFUpload({ // Backend Settings 设置处理上传图片的url地址。 upload_url: "fileUpLoadTest.ashx?action=up", post_params: { "ASPSESSID": "<%=Session.SessionID %>" }, // File Upload Settings file_size_limit: "2 MB",//上传文件的最大图片大小 file_types: "*.jpg",//上传图片类型 file_types_description: "JPG Images", file_upload_limit: 0, // Zero means unlimited // 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. swfupload_preload_handler: preLoad, swfupload_load_failed_handler: loadFailed, file_queue_error_handler: fileQueueError, file_dialog_complete_handler: fileDialogComplete, upload_progress_handler: uploadProgress, upload_error_handler: uploadError, //用户上传图片成功后的回调函数函数。 upload_success_handler: function uploadSuccess(file, serverData) { var files= serverData.split(':'); alert(files[1]); //document.getElementById("divContainer").style.width = files[2] + "px";//js实现 //document.getElementById("divContainer").style.height = files[3] + "px"; //document.getElementById("divContainer").style.backgroundImage = "url(" + files[1] + ")"; //设置div的宽度和高度和背景图片的宽度和高度一致。 $("#divContainer").css("width", files[2] + "px"); $("#divContainer").css("height", files[3] + "px"); //设置div的backgroundImage的url。不能直接设置地址,必须加上"url()" $("#divContainer").css("backgroundImage", "url(" + files[1] + ")"); //获取用户上传文件的文件名,用于截取头像时读取源图片。 filename=files[4]; }, upload_complete_handler: uploadComplete, // Button settings button_image_url: "/lib/swfupload/images/XPButtonNoText_160x22.png", button_placeholder_id: "spanButtonPlaceholder", button_width: 160, button_height: 22, button_text: '<span class="button">Select Images <span class="buttonSmall">(2 MB Max)</span></span>', 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, // Flash Settings flash_url: "/lib/swfupload/swfupload.swf", // Relative to this file这里须要注意文件路径。 flash9_url: "/lib/swfupload/swfupload_FP9.swf", // Relative to this file custom_settings: { upload_target: "divFileProgressContainer" }, // Debug Settings debug: false }); }
//-------------------------------下面是图片截取的前端代码------------------------------------------ $(function () { $(function () { //使用jq-ui 实现截取头像的div的移动和改变大小 $("#divCut").draggable({ containment: "parent" }).resizable({ containment: "#divContainer", aspectRatio: 1 / 1 }); $("#btnCut").click(function () { //经过offset()方法返回的相对于浏览器的top和left值来获取截取头像div相对于图片的位置。 var divtop = $("#divCut").offset().top - $("#divContainer").offset().top; var divleft = $("#divCut").offset().left - $("#divContainer").offset().left; var divwidth = $("#divCut").width(); var divHeight = $("#divCut").height(); //点击按钮发送ajax请求。 $.post("fileUpLoadTest.ashx", { "action": "cut", "top": divtop, "left": divleft, "width": divwidth, "height": divHeight, "filename": filename }, function (data) {
//返回截取图片的路径并设置给img标签 $("#imgcut").attr("src", data); }) }); }) }) </script>
页面控件布局(这里只是简单的实现,具体页面的设计并未设置):jquery
<body> <form id="form1" runat="server"> <div> <span id="spanButtonPlaceholder"></span> </div> <div id="divFileProgressContainer" style="height: 75px;"></div> <div id="divContainer"><div id="divCut" style="border:2px solid red;width:200px;height:200px"></div></div> <input type="button" id="btnCut" value="截取" /> </form> <img id="imgcut" alt="Alternate Text" /> </body>
后台代码:web
context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); //获取客户端的action,经过判断action来判断用户是上传图片仍是头像截取 string action = context.Request["action"];
//图片上传--经过action来判断的 if (context.Request["action"]=="up") { HttpPostedFile file = context.Request.Files["Filedata"];//经过Filedata来获取用户上传上来的文件 string name=file.FileName;//获取上传文件的全文件名 file.SaveAs(context.Server.MapPath("/img/" + name));//文件保存到项目根目录下的/img/文件夹下,以用户上传的图片名做文件的文件名。这里须要注意重复文件名的问题。具体能够经过把用户上传的文件进行md5处理后做为文件名,这样重复的文件屡次上传不会保存多份,相同文件名但文件不一样的经过md5处理后文件名也就不同了。
Image img = Image.FromStream(file.InputStream);
//像客户端输出数据,返回ok表示成功,而后返回上传文件的路径在客户端能够设置div的背景图片的url为文件路径,并同时返回图片的大小来设置前端div的大小,最后还返回保存上传文件的文件名。并在头像截取的时候传递到后台。
context.Response.Write("ok:" + "/img/" + name + ":" + (img.Width) + ":" + (img.Height) + ":" + name); }
//图片截取 else if (context.Request["action"]=="cut") { string topstr = context.Request["top"]; string filename = context.Request["filename"]; int top = Convert.ToInt32(context.Request["top"]); int left = Convert.ToInt32(context.Request["left"]); int width = Convert.ToInt32(context.Request["width"]); int height = Convert.ToInt32(context.Request["height"]); using (Image oldImg = Image.FromFile(context.Server.MapPath("/img/" + filename))) { using (Bitmap bitmap=new Bitmap(width,height)) { using (Graphics g=Graphics.FromImage(bitmap)) { //g.InterpolationMode = InterpolationMode.High; //g.SmoothingMode = SmoothingMode.AntiAlias; g.DrawImage(oldImg, new Rectangle(0, 0, width, height), new Rectangle(left, top, width, height), GraphicsUnit.Pixel); g.Save(); } bitmap.Save(context.Server.MapPath("/img/cut/" + filename)); } } context.Response.Write("/img/cut/" + filename); }
具体实现结果以下:ajax
界面:浏览器
上传图片: 图片截取:异步