本文實(shí)例為大家分享了FormData上傳多個(gè)文件的具體代碼,供大家參考,具體內(nèi)容如下
創(chuàng)新互聯(lián)專注于企業(yè)網(wǎng)絡(luò)營銷推廣、網(wǎng)站重做改版、防城港網(wǎng)站定制設(shè)計(jì)、自適應(yīng)品牌網(wǎng)站建設(shè)、H5場景定制、商城系統(tǒng)網(wǎng)站開發(fā)、集團(tuán)公司官網(wǎng)建設(shè)、成都外貿(mào)網(wǎng)站建設(shè)、高端網(wǎng)站制作、響應(yīng)式網(wǎng)頁設(shè)計(jì)等建站業(yè)務(wù),價(jià)格優(yōu)惠性價(jià)比高,為防城港等各大城市提供網(wǎng)站開發(fā)制作服務(wù)。
由于項(xiàng)目中使用到,特此寫個(gè)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();
//循環(huán)添加到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";
}前端頁面:

請求:

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。
新聞標(biāo)題:使用FormData實(shí)現(xiàn)上傳多個(gè)文件
文章路徑:http://chinadenli.net/article28/gdssjp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站策劃、網(wǎng)站營銷、網(wǎng)站收錄、企業(yè)建站、云服務(wù)器、網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)