Home  >  Article  >  Java  >  How to send one or more files to the background in one ajax

How to send one or more files to the background in one ajax

巴扎黑
巴扎黑Original
2016-12-02 11:43:062230browse

在开发的时候我们可能都需要传一些文件到后台,然后又不希望刷新页面,那么我们可用ajax传文件流到后台。

我们可以在js中用FormData这个对象来包装文件流对象。

1.首先我们怎么能够让file能够选择多个文件呢,很简单加个multiple属性就行,这样就可以再选文件的时候选择多个文件了。

<input type="file" id="images" name="images" multiple />

 2.接着,我们要在js中获得这个文件对象

$("#submit").click(function() {
var paths = document.getElementById("images").files;
if(paths.length==0)
{
alert("请选择文件");
return;
}
var formData = new FormData();
//alert(paths.length);
        //我们遍历每一个文件对象
for (var i = 0; i < paths.length; i++) {
var file = paths[i];
//alert(file.type);
               //用正则表达式判断文件的类型是否是图片,这里大家可以自由发挥
if (!new RegExp("image/*").test(file.type)) {
alert("请注意,上传的文件一定要是图片文件");
return;
} 
}
//alert("开始上传");
       //我们可以预先定义一个FormData对象
var formData=new FormData();
for(var i=0;i<paths.length;i++)
{
                //将每个文件设置一个string类型的名字,放入到formData中,这里类似于setAttribute("",Object)
formData.append(paths[i].name,paths[i]);
}
$.ajax({
url: &#39;/MySoleSys/mainServlet&#39;,
        type: &#39;POST&#39;,
cache: false,
        data:formData,
                 //这个参数是jquery特有的,不进行序列化,因为我们不是json格式的字符串,而是要传文件
processData: false,
               //注意这里一定要设置contentType:false,不然会默认为传的是字符串,这样文件就传不过去了
contentType: false,
success:function(returnedData)
{ 
      if($.trim(returnedData)==$.trim("success"))
      {
       alert("上传图片成功");
window.location.href="/MySoleSys/mainboard/index.html"
}
else if($.trim(returnedData)==$.trim("fail"))
alert("上传图片失败");    
}
});
});

 3.下一步我们肯定要在后台接收文件啦,这里我已开始用action接受,但总是收不到文件,也许是struts2过滤器的问题,改成用Servlet接受就成了。。。郁闷。。,后台我们用request.getParts()接受FormData.

Collection<Part>parts=request.getParts();
Iterator<Part> it=parts.iterator();
while(it.hasNext())
{
Part img=it.next();
/**
* 开始传图片到服务器端文件夹。
*/
file=new File(path+"\\"+img.getName());
fos=new FileOutputStream(file);
        //可以从每个part中获得文件的输入流,获得输入流之后想怎么搞就怎么搞都可以啦
imgis=img.getInputStream();
int len=-1;
while((len=imgis.read(bytes))!=-1)
{
fos.write(bytes,0, len);
}
fos.flush();
}

还有一点就是如果报一次请求的数据量太大了的话,可以在struts.xml配置struts.multipart.maxSize属性,把他的值改大一点就可以了。

<constant name="struts.multipart.maxSize" value="9000000" />


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn