即使没有人为你鼓掌,也要优雅的谢幕,感谢自己的认真付出。我们未来都是巨星,别人信不信无所谓,我们自己必须坚信!
本文实例为大家分享了FormData上传多个文件的具体代码,供大家参考,具体内容如下
由于项目中使用到,特此写个Demo
html代码:
<html> <head> <title>Title</title> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> </head> <body> <form enctype="multipart/form-data" id="form_example"> <input type="file" id="files" multiple/><br/><br/> <input type="submit" value="提交"/> </form> <div id='file-list-display'></div> </body> </html>
js代码:
<script type="text/javascript"> $(document).ready(function () { var fileList = []; var fileCatcher = document.getElementById('form_example'); var files = document.getElementById("files"), renderFileList; var fileListDisplay = document.getElementById('file-list-display'), sendFile; fileCatcher.addEventListener("submit", function (event) { event.preventDefault(); //上传文件 sendFile(); }); files.addEventListener("change", function (event) { for (var i = 0; i < files.files.length; i++) { fileList.push(files.files[i]); } renderFileList(); }); renderFileList = function () { fileListDisplay.innerHTML = ''; fileList.forEach(function (file, index) { var fileDisplayEl = document.createElement("p"); fileDisplayEl.innerHTML = (index + 1) + ":" + file.name; fileListDisplay.appendChild(fileDisplayEl); }) }; sendFile = function () { var formData = new FormData(); var request = new XMLHttpRequest(); //循环添加到formData中 fileList.forEach(function (file) { formData.append('files', file, file.name); }) request.open("POST", "/test/upload.do"); request.send(formData); } }) </script>
后端使用Spring MVC接收前端文件
配置multipart解析器:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8"/>
Controller:
@RequestMapping("/upload.do") @ResponseBody public Object upload(@RequestParam MultipartFile[] files) { System.out.println(files.length); return "ok"; }
前端页面:
请求:
本文使用FormData实现上传多个文件到此结束。青春,仲夏盛开的火红石榴花;外形无比绚丽,不为炽热,害怕寂寞像盛满豪言壮语的金罍,承载了太多,太过于娇艳,以至于被从玻璃镜折射出来的光芒折煞了自己,青春,待续的代名词。小编再次感谢大家对我们的支持!