问题:jquery Ajax serialize()表单进行序列化方式上传文件
通过$(‘#example’).serialize()可以对form表单进行序列化,从而将form表单中的所有参数传递到服务端,只能传递一般的参数,上传文件的文件流是无法被序列化并传递的。
不过如今主流浏览器都开始支持一个叫做FormData的对象,有了这个FormData,我们就可以轻松地使用Ajax方式进行文件上传了。
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form id="example">
username: <input type="text" name="username"/><br/>
password: <input type="password" name="password"/><br/>
file: <input type="file" id="files" multiple/><br/>
<input type="submit" value="提交"/>
</form>
<div id='file-list-display'></div>
<script type="text/javascript">
$(function () {
let fileList = [];
const fileCatcher = $('#example');
const files = $("#files");
const fileListDisplay = $('#file-list-display');
fileCatcher.on("submit", function (event) {
event.preventDefault();
//上传文件
let formData = new FormData(fileCatcher[0]);
//循环添加到formData中
fileList.forEach(function (file) {
formData.append('files', file, file.name);
})
const request = new XMLHttpRequest();
request.open("POST", "upload");
request.send(formData);
});
files.on("change", function (event) {
for (var i = 0; i < files[0].files.length; i++) {
fileList.push(files[0].files[i]);
}
let content = '';
fileList.forEach(function (file, index) {
content += '<p>' + (index + 1) + ":" + file.name + '</p>';
})
fileListDisplay.html(content);
});
})
</script>
</body>
</html>
源码
https://github.com/ncc0706/front-end/blob/master/form-data/form-data-2-jq.html
网友评论