ajax实现excel文件上传|怎么样通过jQuery Ajax实现上传文件

ajax实现excel文件上传|怎么样通过jQuery Ajax实现上传文件的第1张示图

⑴ ajax怎样提交form表单与实现文件上传

Ajax 提交form方式可以来将form表单序列化源 然后将数据通过data提交至后台,例如:

⑵ 怎么样通过jQuery Ajax实现上传文件

Query Ajax在web应用开发中很常用,它主要包括有ajax,get,post,load,getscript等等这几种常用无刷新操作方法,接下来通过本文给大家介绍jquery ajax 上传文件处理方式。FormData对象XMLHttpRequest Level 2添加了一个新的接口FormData.利用FormData对象,我们可以通过javaScript用一些键值对来模拟一系列表单控件,我们还可以使用XMLHttpRequest的send()方法来异步的提交这个”表单”.比起普通的ajax,使用FormData的最大优点就是我们可以异步上传一个二进制文件.所有主流浏览器的较新版本都已经支持这个对象了,比如Chrome 7+、Firefox 4+、IE 10+、Opera 12+、Safari 5+。之前都是用原生js的XMLHttpRequest写的请求XMLHttpRequest方式xhr.open("POST", uri, true);xhr.onreadystatechange = function() {if (xhr.readyState == 4 && xhr.status == 200) {// Handle response.alert(xhr.responseText); // handle response.}};fd.append('myFile', file);// Initiate a multipart/form-data uploadxhr.send(fd);其实jquery的ajax也可以支持到的,关键是设置:processData 和 contentType 。ajax方式var formData = new FormData();var name = $("input").val();formData.append("file",$("#upload")[0].files[0]);formData.append("name",name);$.ajax({url : Url,type : 'POST',data : formData,// 告诉jQuery不要去处理发送的数据processData : false,// 告诉jQuery不要去设置Content-Type请求头contentType : false,beforeSend:function(){console.log("正在进行,请稍候");},success : function(responseStr) {if(responseStr.status===0){console.log("成功"+responseStr);}else{console.log("失败");}},error : function(responseStr) {console.log("error");}});

⑶ 如何用Ajax实现多文件上传

jquery 实现多个上传文件教程:首先创建解决方案,添加jquery的js和一些资源文件(如图片和进度条显示等):12345 jquery-1.3.2.min.js jquery.uploadify.v2.1.0.js jquery.uploadify.v2.1.0.min.js swfobject.js uploadify.css1、页面的基本代码如下这里用的是aspx页面(html也是也可的)页面中引入的js和js函数如下:1234567<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script> <script src="js/jquery.uploadify.v2.1.0.js" type="text/javascript"></script> <script src="js/jquery.uploadify.v2.1.0.min.js" type="text/javascript"></script> <script src="js/swfobject.js" type="text/javascript"></script> <link href="css/uploadify.css" rel="stylesheet" type="text/css" /> </script>js函数:12345678910111213141516171819202122232425262728293031<script type="text/javascript"> $(document).ready(function () { $("#uploadify").uploadify({ 'uploader': 'image/uploadify.swf', //uploadify.swf文件的相对路径,该swf文件是一个带有文字BROWSE的按钮,点击后淡出打开文件对话框 'script': 'Handler1.ashx',// script : 后台处理程序的相对路径 'cancelImg': 'image/cancel.png', 'buttenText': '请选择文件',//浏览按钮的文本,默认值:BROWSE。 'sizeLimit':999999999,//文件大小显示 'floder': 'Uploader',//上传文件存放的目录 'queueID': 'fileQueue',//文件队列的ID,该ID与存放文件队列的div的ID一致 'queueSizeLimit': 120,//上传文件个数限制 'progressData': 'speed',//上传速度显示 'auto': false,//是否自动上传 'multi': true,//是否多文件上传 //'onSelect': function (e, queueId, fileObj) { // alert("唯一标识:" + queueId + "\r\n" + // "文件名:" + fileObj.name + "\r\n" + // "文件大小:" + fileObj.size + "\r\n" + // "创建时间:" + fileObj.creationDate + "\r\n" + // "最后修改时间:" + fileObj.modificationDate + "\r\n" + // "文件类型:" + fileObj.type); // } 'onQueueComplete': function (queueData) { alert("文件上传成功!"); return; } }); });页面中的控件代码:12345678910111213<body> <form id="form1" runat="server"> <div id="fileQueue"> </div> <div> <p> <input type="file" name="uploadify" id="uploadify"/> <input id="Button1" type="button" value="上传" onclick="javascript: $('#uploadify').uploadifyUpload()" /> <input id="Button2" type="button" value="取消" onclick="javascript:$('#uploadify').uploadifyClearQueue()" /> </p> </div> </form> </body>函数主要参数:12345678910111213141516171819$(document).ready(function() { $('#fileInput1').fileUpload({ 'uploader': 'uploader.swf',//不多讲了 'script': '/AjaxByJQuery/file.do',//处理Action 'cancelImg': 'cancel.png', 'folder': '',//服务端默认保存路径 'scriptData':{'methed':'uploadFile','arg1','value1'}, //向后台传递参数,methed,arg1为参数名,uploadFile,value1为对应的参数值,服务端通过request["arg1"] 'buttonText':'UpLoadFile',//按钮显示文字,不支持中文,解决方案见下 //'buttonImg':'图片路径',//通过设置背景图片解决中文问题,就是把背景图做成按钮的样子 'multi':'true',//多文件上传开关 'fileExt':'*.xls;*.csv',//文件过滤器 'fileDesc':'.xls',//文件过滤器 详解见文档 'onComplete' : function(event,queueID,file,serverData,data){ //serverData为服务器端返回的字符串值 alert(serverData); } }); });后台一般处理文件:1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Net; using System.Web; using System.Web.Services; namespace fupload { /// <summary> /// Handler1 的摘要说明 /// </summary> public class Handler1 : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; HttpPostedFile file = context.Request.Files["Filedata"];//对客户端文件的访问 string uploadPath = HttpContext.Current.Server.MapPath(@context.Request["folder"])+"\\";//服务器端文件保存路径 if (file != null) { if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath);//创建服务端文件夹 } file.SaveAs(uploadPath + file.FileName);//保存文件 context.Response.Write("上传成功"); } else { context.Response.Write("0"); } } public bool IsReusable { get { return false; } } } }以上方式基本可以实现多文件的上传,大文件大小是在控制在10M以下/。

⑷ 如何用ajax上传文件

引入ajaxfileupload.js

jQuery.extend({createUploadIframe:function(id,uri){//createframevarframeId='jUploadFrame'+id;if(window.ActiveXObject){vario=document.createElement('<iframeid="'+frameId+'"name="'+frameId+'"/>');if(typeofuri=='boolean'){io.src='javascript:false';}elseif(typeofuri=='string'){io.src=uri;}}else{vario=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);returnio},createUploadForm:function(id,fileElementId){//createformvarformId='jUploadForm'+id;varfileId='jUploadFile'+id;varform=$('<formaction=""method="POST"name="'+formId+'"id="'+formId+'"enctype="multipart/form-data"></form>');varoldElement=$('#'+fileElementId);varnewElement=$(oldElement).clone();$(oldElement).attr('id',fileId);$(oldElement).before(newElement);$(oldElement).appendTo(form);//setattributes$(form).css('position','absolute');$(form).css('top','-1200px');$(form).css('left','-1200px');$(form).appendTo('body');returnform;},addOtherRequestsToForm:function(form,data){//addextraparametervaroriginalElement=$('<inputtype="hidden"name=""value="">');for(varkeyindata){name=key;value=data[key];varcloneElement=originalElement.clone();cloneElement.attr({'name':name,'value':value});$(cloneElement).appendTo(form);}returnform;},ajaxFileUpload:function(s){//TODOintroceglobalsettings,,notonlytimeouts=jQuery.extend({},jQuery.ajaxSettings,s);varid=newDate().getTime()varform=jQuery.createUploadForm(id,s.fileElementId);if(s.data)form=jQuery.addOtherRequestsToForm(form,s.data);vario=jQuery.createUploadIframe(id,s.secureuri);varframeId='jUploadFrame'+id;varformId='jUploadForm'+id;//Watchforanewsetofrequestsif(s.global&&!jQuery.active++){jQuery.event.trigger("ajaxStart");}varrequestDone=false;//Createtherequestobjectvarxml={}if(s.global)jQuery.event.trigger("ajaxSend",[xml,s]);//WaitforaresponsetocomebackvaruploadCallback=function(isTimeout){vario=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;}elseif(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;varstatus;try{status=isTimeout!="timeout"?"success":"error";//if(status!="error"){//processthedata()vardata=jQuery.uploadHttpData(xml,s.dataType);//Ifalocalcallbackwasspecified,fireitandpassitthedataif(s.success)s.success(data,status);//Firetheglobalcallbackif(s.global)jQuery.event.trigger("ajaxSuccess",[xml,s]);}elsejQuery.handleError(s,xml,status);}catch(e){status="error";jQuery.handleError(s,xml,status,e);}//Therequestwascompletedif(s.global)jQuery.event.trigger("ajaxComplete",[xml,s]);//HandletheglobalAJAXcounterif(s.global&&!–jQuery.active)jQuery.event.trigger("ajaxStop");//Processresultif(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}}//Timeoutcheckerif(s.timeout>0){setTimeout(function(){//if(!requestDone)uploadCallback("timeout");},s.timeout);}try{//vario=$('#'+frameId);varform=$('#'+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){vardata=!type;data=type=="xml"||data?r.responseXML:r.responseText;//Ifthetypeis"script",evalitinglobalcontextif(type=="script")jQuery.globalEval(data);//GettheJavaScriptobject,ifJSONisused.if(type=="json"){//,//youhavetodeletethe'<pre></pre>'tag.//ThepretaginChromehasattribute,sohavetouseregextoremovevardata=r.responseText;varrx=newRegExp("<pre.*?>(.*?)</pre>","i");varam=rx.exec(data);//thisisthedesireddataextractedvardata=(am)?am[1]:"";//theonlysubmatchoremptyeval("data="+data);}//evaluatescriptswithinhtmlif(type=="html")jQuery("<div>").html(data).evalScripts();//alert($('param',data).each(function(){alert($(this).attr('value'));}));returndata;}})

2.引入上传文件所需的jar

7.获取之后怎么处理自己看着办咯,我只能帮到这里了

⑸ JS怎样用AJAX上传文件

实际上AJAX本身是没办法上传文件的…一般上传都是用FOMR…来实现类似AJAX….

如果不用FORM用JS , 可以使用下面这几个工具:

WebUploader:http://fex..com/webuploader/

pluploader:http://www.plupload.com

⑹ ajax怎么提交带文件上传表单

上传的文件是没有办法和表单内容一起异步的,可考虑使用jquery的ajaxfileupload,或是其他的插件,异步上传文件后,然后再对表单进行操作。

⑺ java 使用 AjaxUpload.js 实现上传文档的时候需要注意哪些

ajax是无法提交文件的,所以在上传图片并预览的时候,我们经常使用Ifame的方法实现看似异步的效果。但是这样总不是很方便的,AjaxFilleUpload.js对上面的方法进行了一个包装,使得我们不用去管理Iframe的一系列操作,也不用影响我们的页面结构,实现异步的文件提交。 html: 复制代码 代码如下: <input type="file" name="upload" hidden="hidden" id="file_upload" accept=".zip" />js: 复制代码 代码如下: $.ajaxFileUpload({ url:'${pageContext.request.contextPath}/Manage/BR_restorePic.action', //需要链接到服务器地址 secureuri:false, fileElementId:'file_upload', //文件选择框的id属性 dataType: 'text', //服务器返回的格式,可以是json、xml success: function (data, status) //相当于java中try语句块的用法 { $('#restoreDialog').html(data); //alert(data); }, error: function (data, status, e){ //相当于java中catch语句块的用法 $('#restoreDialog').html("上传失败,请重试"); } });这个方法还会出现一个问题,就是input只能使用一次的问题,input第二次的onchange将不会被执行,这应该是与浏览器的有关,解决办法就是替换这个input 像这样: 复制代码 代码如下: $('#file_upload').replaceWith('<input type="file" name="upload" hidden="hidden" id="file_upload" accept=".zip" />');

⑻ 能用ajax以POST实现文件上传吗

可以XMLHttpRequest2中数据类型支持formData,formData就相当于原来的Form表单提交的格式也跟form表单一样,可以通过它来上传文件

⑼ 怎么用ajax提交file文件上传

上传的文件是没有办法和表单内容一起异步的,可考虑使用jquery的ajaxfileupload,或是其他的插件,异步上传文件后,然后再对表单进行操作。

⑽ 如何使用AjaxFileupload插件上传文件,在服务器servlet中读取并返回客户端的功能

servlet可以直接读取客户端的文件的,不过需要用到表单,ajaxfileupload中好像自带表单,所以应该使用接口或者方法就行了吧

未经允许不得转载:山九号 » ajax实现excel文件上传|怎么样通过jQuery Ajax实现上传文件

赞 (0)