一个ajax实现表单上传文件的神器 formdata

时间:2023-12-10 09:15:44

通过传统的form表单提交的方式上传文件:

  1. $.ajax({
  2. url : "http://localhost:8080/STS/rest/user",
  3. type : "POST",
  4. data : $( '#postForm').serialize(),
  5. success : function(data) {
  6. $( '#serverResponse').html(data);
  7. },
  8. error : function(data) {
  9. $( '#serverResponse').html(data.status + " : " + data.statusText + " : " + data.responseText);
  10. }
  11. });
  12. 如上,通过$('#postForm').serialize()可以对form表单进行序列化,从而将form表单中的所有参数传递到服务端。
    但是上述方式,只能传递一般的参数,上传文件的文件流是无法被序列化并传递的。
    不过如今主流浏览器都开始支持一个叫做FormData的对象,有了这个FormData,我们就可以轻松地使用Ajax方式进行文件上传了。

下面为jsp代码

  1. <form id= "uploadForm">
  2. <p >指定文件名: <input type="text" name="filename" value= ""/></p >
  3. <p >上传文件: <input type="file" name="file"/></ p>
  4. <input type="button" value="上传" onclick="doUpload()" />
  5. </form>

下面为js代码

  1. function doUpload() {
  2. var formData = new FormData($( "#uploadForm" )[0]);
  3. $.ajax({
  4. url: 'http://localhost:8080/cfJAX_RS/rest/file/upload' ,
  5. type: 'POST',
  6. data: formData,
  7. async: false,
  8. cache: false,
  9. contentType: false,
  10. processData: false,
  11. success: function (returndata) {
  12. alert(returndata);
  13. },
  14. error: function (returndata) {
  15. alert(returndata);
  16. }
  17. });
  18. }

可以轻松实现上传。

一下为我自己写的实例,已经过亲身验证:

function doCheck(){
var formData = new FormData($( "#upfile" )[0]);
$.ajax({
type:"POST",
url: "${ctx}/user/returnRowsNum",
data:formData,
async:false,
cache: false,
contentType: false,
processData: false,
success:function(data){
if(data){
var numb = data.num
var ti = 20*numb/900
alert(data.num);
alert(numb+"条数据,预计耗时"+ti.toFixed(1)+"分钟,期间请勿操作页面,闹心等待")
}
}
});
}

jsp代码:

<form name="upfile" id="upfile" method="post" enctype="multipart/form-data" onsubmit="return checkSub()" action="${ctx}/user/importUser?1=1" >
<input type="hidden" name="path" id="path" value=""/>
<input type="hidden" name="orgId" id="orgId" value="${orgId}"/>
<div id="mainwindowhidden">
<div class="suggestion">
<span class="sugicon"><span class="strong colorgorning2">当前操作提示:</span><span class="padding-left5 colorgorningage">上传文件格式为xls,单次导入用户数不能大于1000条。</span></span>
</div>
<div class="sugtitle-line"></div>
<div class="formdiv" >
<table border="0" width="100%">
<tr class="trstyle2">
<td class="trtitle01" width="20%"><span class="requiredLabelClass">*</span> 选择文件</td>
<td class="trtitle02" width="80%"><input type="file" name="upfilepath" value="" maxlength="200" size="50" class="infoInput"></td>
</tr>
</table>
</div>
</div>
<div id="downbotton">
<div id="subbotton">
<table border="0" width="100%">
<tr id="bottonsubmit">
<td id="right"><input type="submit" name="Submit" id="submitbotton" onClick="doCheck()" value="确认上传1" class="buttonface" title="确认上传"/></td>
<td id="left" class="padding-left5"><input type="reset" name="reset" onClick="javascript:cancelUpload();" id="release" value="取消上传" class="buttonface" title="取消上传" /></td>
</tr>
</table>
</div>
</div>
</form>