jQuery ajax + ajaxfileupload.js插件 实现无刷新文件上传
2016-06-04 18:30
1051 查看
jQuery ajax + ajaxfileupload.js插件 实现无刷新文件上传
这里以上传图片为例,其它多媒体文件类似==== aspx 页面部分代码如下 =====
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="InfoEdit.aspx.cs" Inherits="Admin.InfoEdit" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>编辑信息</title> <script src="/Js/jquery-1.11.0.min.js" type="text/javascript"></script> <script src="/Js/ajaxfileupload.js" type="text/javascript"></script> </head> <body> <!--<form id="form1"> 带不带下面的enctype都可以,推荐带上-->
<form id="form1" enctype="multipart/form-data"> <div> <table> <tr> <td><em class="red">*</em>下载地址 </td> <td align="left"> <input id="PicFile" name="PicFile" type="file" class="w200" /> 路径<input id="FilePath" type="text" class="w200" value="" readonly="true" /> 大小<input id="FileSize" type="text" class="w200" value="" readonly="true" /> <input type="button" id="buttonUplod" class="w200" value="上传" /> </td> </tr> <tr> <th></th> <th align="left" style="padding: 20px;"> <input type="button" value=" 保存 " id="btnOk" /> <input type="button" value=" 取消 " style="margin-left: 50px;" id="btnCancel" /> </th> </tr> </table> </div> </form> <script type="text/javascript"> $(document).ready(function () { GetData(); $("#btnOk").click(function () { DataEdit(); }); $("#btnCancel").click(function () { window.location.href = "Infos.aspx"; }); }); function GetData() { var id = getQueryString("id") || 0; if (id == 0) { return; } var data = {}; data.method = "GetData"; data.id = id; ajaxProcess("/InfoEdit.aspx?", data, function callSuccess(oRet) { var result = oRet.Result[0]; if (result != null) { $("#FilePath").val(result.Url); } }, function callError(e) { alert(e); }); } function DataEdit() { var id = getQueryString("id") || 0; var size = $("#FileSize").val(); var picPath = $("#FilePath").val(); if (!picPath) { showDialog("没有上传文件"); return; } var data = {}; data.method = "DataEdit"; data.id = id, data.size = size; data.contents = contents; data.picfile = picPath; ajaxProcess("?", data, function (oRet) { if (oRet.Error || oRet.Result < 0) { showDialog(oRet.Error || "操作失败"); return; } showDialog("操作成功", 1, 0, "提示", function () { window.location.href = "Infos.aspx"; }); }, function (ex) { alert(ex); }); } </script> <script type="text/javascript"> $("#buttonUplod").click(function () { $.ajaxFileUpload({ url: 'Audioupload.aspx?type=2', //你处理上传文件的服务端 type=1 sys sound type=2 info secureuri: false, //与页面处理代码中file相对应的ID值 fileElementId: 'PicFile', dataType: 'json', //返回数据类型:text,xml,json,html,scritp,jsonp五种 success: function (data) { //alert(data.path); $("#FilePath").val(data.path); $("#FileSize").val(data.size); if (data.status == "error") { alert(data.msg); } } }); }); </script> </body> </html>
====== Picupload.aspx 文件如下 =====
using System; using System.Configuration; using System.Drawing; using System.IO; using System.Web; using Admin.App_Codes; using Utility; namespace Admin { public partial class Picupload : PageBase { protected override void OnInit(EventArgs e) { PowerPageId = 10034; base.OnInit(e); } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { try { var type = Request["type"]; if (Request.UrlReferrer==null || Request.UrlReferrer.ToString().Length < 1 || type==null) { Response.Write("该页面不能直接访问"); Response.End(); } var infoPicPath = ConfigurationManager.AppSettings["InfoPicPath"].ToString(); if (type == "2") { Upload(infoPicPath); } } catch (Exception ex) { var response = "{\"status\" : \"error\", \"msg\": " + "\"" + ex.Message.ToString() + "\"}"; Response.Write(response); Response.End(); } } } private void Upload(string picPath) { var response = ""; try { HttpFileCollection files = Request.Files; if (files.Count > 0) { HttpPostedFile file = files[0]; string tmpPath = Server.MapPath(picPath); string fileName = Path.GetFileName(file.FileName); var isSafe = PicCheck(file); if (isSafe) { file.SaveAs(tmpPath + fileName); //response = "{\"status\" : \"success\", \"path\": " + "\"" + picPath + fileName + "\"}"; response = "{\"status\" : \"success\", \"path\": " + "\"" + picPath + fileName + "\",\"size\": " + "\"" + file.ContentLength + "\"}"; } else { response = "{\"status\" : \"error\", \"msg\": " + "\"图片格式不对或大小超限\"}"; } Response.Clear(); Response.Write(response); } } catch (Exception ex) { response = "{\"status\" : \"error\", \"msg\": " + "\"" + ex.Message.ToString() + "\"}"; Response.Write(response); Response.End(); } } private bool PicCheck(HttpPostedFile picFile) { var isSafe = false; var picMaxSize = ConfigurationManager.AppSettings["PicMaxSize"].ToString().ToInt32(); string fileName = Path.GetFileName(picFile.FileName); string picext = Path.GetExtension(fileName).ToLower(); if (picext == ".jpg" || picext == ".gif" || picext == ".bmp" || picext == ".png") { isSafe = true; } else { isSafe = false; return isSafe; } if (picFile.ContentLength < picMaxSize) { isSafe = true; } else { isSafe = false; return isSafe; } //图片尺寸检查 Stream picstream = picFile.InputStream; Image img = Image.FromStream(picstream); if (img.Width > 0 && img.Height > 0) { isSafe = true; //picstream.Close(); //picstream.Flush(); } else { isSafe = false; //picstream.Close(); //picstream.Flush(); } return isSafe; } } }
===== ajaxfileupload.js 文件如下 ====
ajaxfileupload.jsjQuery.extend({ createUploadIframe: function (id, uri) { //create frame var frameId = 'jUploadFrame' + id; if (window.ActiveXObject) { var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />'); if (typeof uri == 'boolean') { io.src = 'javascript:false'; } else if (typeof uri == 'string') { io.src = uri; } } else { var io = document.createElement('iframe'); io.id = frameId; io.name = frameId; } io.style.position = 'absolute'; io.style.top = '-1000px'; io.style.left = '-1000px'; document.body.appendChild(io); return io }, createUploadForm: function (id, fileElementId) { //create form var formId = 'jUploadForm' + id; var fileId = 'jUploadFile' + id; var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'); var oldElement = $('#' + fileElementId); var newElement = $(oldElement).clone(); $(oldElement).attr('id', fileId); $(oldElement).before(newElement); $(oldElement).appendTo(form); //set attributes $(form).css('position', 'absolute'); $(form).css('top', '-1200px'); $(form).css('left', '-1200px'); $(form).appendTo('body'); return form; }, addOtherRequestsToForm: function (form, data) { // add extra parameter var originalElement = $('<input type="hidden" name="" value="">'); for (var key in data) { name = key; value = data[key]; var cloneElement = originalElement.clone(); cloneElement.attr({ 'name': name, 'value': value }); $(cloneElement).appendTo(form); } return form; }, ajaxFileUpload: function (s) { // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout s = jQuery.extend({}, jQuery.ajaxSettings, s); var id = new Date().getTime() var form = jQuery.createUploadForm(id, s.fileElementId); if (s.data) form = jQuery.addOtherRequestsToForm(form, s.data); var io = jQuery.createUploadIframe(id, s.secureuri); var frameId = 'jUploadFrame' + id; var formId = 'jUploadForm' + id; // Watch for a new set of requests if (s.global && !jQuery.active++) { jQuery.event.trigger("ajaxStart"); } var requestDone = false; // Create the request object var xml = {} if (s.global) jQuery.event.trigger("ajaxSend", [xml, s]); // Wait for a response to come back var uploadCallback = function (isTimeout) { var io = document.getElementById(frameId); try { if (io.contentWindow) { xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null; xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document; } else if (io.contentDocument) { xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null; xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document; } } catch (e) { jQuery.handleError(s, xml, null, e); } if (xml || isTimeout == "timeout") { requestDone = true; var status; try { status = isTimeout != "timeout" ? "success" : "error"; // Make sure that the request was successful or notmodified if (status != "error") { // process the data (runs the xml through httpData regardless of callback) var data = jQuery.uploadHttpData(xml, s.dataType); // If a local callback was specified, fire it and pass it the data if (s.success) s.success(data, status); // Fire the global callback if (s.global) jQuery.event.trigger("ajaxSuccess", [xml, s]); } else jQuery.handleError(s, xml, status); } catch (e) { status = "error"; jQuery.handleError(s, xml, status, e); } // The request was completed if (s.global) jQuery.event.trigger("ajaxComplete", [xml, s]); // Handle the global AJAX counter if (s.global && ! --jQuery.active) jQuery.event.trigger("ajaxStop"); // Process result if (s.complete) s.complete(xml, status); jQuery(io).unbind() setTimeout(function () { try { $(io).remove(); $(form).remove(); } catch (e) { jQuery.handleError(s, xml, null, e); } }, 100) xml = null } } // Timeout checker if (s.timeout > 0) { setTimeout(function () { // Check to see if the request is still happening if (!requestDone) uploadCallback("timeout"); }, s.timeout); } try { // var io = $('#' + frameId); var form = $('#' + formId); $(form).attr('action', s.url); $(form).attr('method', 'POST'); $(form).attr('target', frameId); if (form.encoding) { form.encoding = 'multipart/form-data'; } else { form.enctype = 'multipart/form-data'; } $(form).submit(); } catch (e) { jQuery.handleError(s, xml, null, e); } if (window.attachEvent) { document.getElementById(frameId).attachEvent('onload', uploadCallback); } else { document.getElementById(frameId).addEventListener('load', uploadCallback, false); } return { abort: function () { } }; }, uploadHttpData: function (r, type) { var data = !type; data = type == "xml" || data ? r.responseXML : r.responseText; // If the type is "script", eval it in global context if (type == "script") jQuery.globalEval(data); // Get the JavaScript object, if JSON is used. if (type == "json") eval("data = " + data); // evaluate scripts within html if (type == "html") jQuery("<div>").html(data).evalScripts(); //alert($('param', data).each(function(){alert($(this).attr('value'));})); return data; } })
=== end ===
相关文章推荐
- jQuery选择器
- jQuery Validate验证框架详解
- jquery,php之间的ajax关系以及json
- jQuery和DOM对象转化
- jQuery实现 全选/全不选
- jQuery EasyUI-validatebox验证框、实现自定义验证
- JQuery.cycle()实现图片轮播简单使用
- Jquery parent方法 IE8 不起作用
- 理解jquery的$.extend()、$.fn和$.fn.extend()
- JavaScript jQuery 入门回顾 2
- jQuery中的.bind()、.live()和.delegate()之间区别分析,学习jquery
- JavaScript jQuery 事件、动画、扩展
- JQuery的异步回调支持 - Promise、Deferred
- js和jquery获取父级元素、子级元素、兄弟元素的方法
- 实现jquery DataTable前后台动态分页
- jquery的each()详细介绍
- jQuery源码解读二
- jQuery+CSS3实现404背景动画特效
- Jquery使用trigger()方法模拟事件
- jQuery Mobile 触摸事件实例