关于ajax 上传文件时parseRequest(request)为null的解决方法

来源:互联网 发布:扭曲验证码识别 python 编辑:程序博客网 时间:2024/06/05 09:25

之前做一个文件上传的网页,因为规定不能用嵌入java语句,所以考虑用ajax

然后是我网页的代码的主要部分,为了方便调试我弄了两个提交按钮,一个是submit到servlet,一个是用ajax提交form到servlet

<body><div><form id="form1" name="form1" method="post" action="/fileUpload/UploadServlet" enctype="multipart/form-data"><input type="file" style="font-size:20px;" id="upfile" name="infile" accept=".jpg , .png , .gif"/><input type="submit" style="font-size:20px;"  value="提交"><input type="button" style="font-size:20px;" onclick="sendValue()" value="提交2" /></form></div><div><input type="button" style="font-size:20px;" onclick="checkValue()" value="刷新文件列表"><div id="result"></div></div><script type="text/javascript" src="js/xhr.js"></script><script type="text/javascript">function sendValue(){      //创建ajax引擎对象      var xhr = createXHR();      //用于存储返回信息      var form = new FormData(document.getElementById("form1"));    //提交表单    var msg="";      //创建ajax状态监听      xhr.onreadystatechange=function(){          if(xhr.readyState==4){              if(xhr.status==200){                  //接受返回字符串                  msg = xhr.responseText;                  //使用返回的字符串信息                  document.getElementById("result").innerHTML=msg;              }          }      };      var author = "xmile";      //准备以POST方式发送请求      xhr.open("post","/fileUpload/UploadServlet?author="+author+"&time="+new Date().getTime());      //设置请求头,只有是POST方式下,才设置该请求头      //xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");      xhr.setRequestHeader("content-type","multipart/form-data; boundary=AxamBi0l3e");     //设置为 post时,就可以在send函数中添加参数列表。当为get时,下面的send中参数为null。      //xhr.send("form="+form);    xhr.send(form);    //alert("here")}</script></body></html>
然后我再服务器端打印parseRequest(request)的内容,结果一直是空的[]

网上收了一大堆都是说web.xml的filter那里要改,可是我根本没写filter

后来在某贴看到大神的回复其他人的做法,将

xhr.setRequestHeader("content-type","multipart/form-data; boundary=AxamBi0l3e");
这一句删掉,我怀着半信半疑试了一下,结果打印parseRequest(request)为[name=b0.jpg, StoreLocation=C:\Users\114520~1.ST-\AppData\Local\Temp\upload_bf6dd0d7_162b_448d_b2f6_daa88aec42a9_00000000.tmp, size=6799 bytes, isFormField=false, FieldName=infile]

终于不是空的了,感动了半天,现在想想,好像表单form里本来就设了属性enctype为multipart/form-data,我们提交ajax请求的时候就没必要再为这个form设一次Content-Type,有点画蛇添足,哈哈~~


阅读全文
0 0
原创粉丝点击