利用html5的FormData对象实现多图上传

<html>
    <head>
        <title>FormData多图上传演示</title>
    </head>
    <body>
     <a href="javascript:newPicture();" >上传新图片</a>
<input id="picture" type="file" style="display: none;" multiple="multiple"> </body> <script type="text/javascript" src="/common/js/jquery.min.js"></script> <script type="text/javascript"> function newPicture(){ $('#picture').click(); }     $('#picture').on('change',function(){ var files= $(this).get(0).files; //如果有选择图片则上传图片 var formData= new FormData(); if(files.length>0){ //formData.append("files",files[0]); for(var i=0;i<files.length;i++){
            //FormData.set 和 append() 的区别在于,如果指定的键已经存在, FormData.set 会使用新值覆盖已有的值,而 append() 会把新值添加到已有值集合的后面。
            //注意:如果你的服务器端是PHP那么为了与php命名习惯一致在名称中需要添加[],如formData.append('files[]',files[i]); formData.append(
'files',files[i]); } var xhr= new XMLHttpRequest(); xhr.open('POST', '/uploadImgAlbums'); xhr.onreadystatechange = function(){ if (xhr.readyState== 4&& xhr.status== 200){ console.log('上传成功'+xhr.responseText); //处理其他数据,这里根据需要进行调整 } }; xhr.send(formData); } }); </script> </html>

看完了页面代码,在看下后端的控制器,我后端使用了spring mvc:

@RequestMapping("uploadImgAlbums")
public void albumUploadImgs(@RequestParam(value = "files", required = true) MultipartFile[] multipartFiles,HttpServletRequest req, HttpServletResponse response){
      for(MultipartFile multipartFile:multipartFiles){
       //打印上传的文件路径
System.out.println(multipartFile.getOriginalFilename());
      //打印文件字节数据
      System.out.println(multipartFile.getBytes());
   }
}

我这里只是简单展示下数据发送到了后端文件上传控制器,剩下的根据项目业务的需求继续进行下去吧。

推荐阅读:https://developer.mozilla.org/zh-CN/docs/Web/API/FormData

https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects

https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHTTPRequest

https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

原文地址:https://www.cnblogs.com/hihtml5/p/6694237.html