//upload2 $("#attachmentUploadBtn2").click(function (even) { //1、通过HTML表单创建FormData对象 自动注入 // var formData = new FormData($("#attachments2")[0]); //2、从零开始创建FormData对象 手动注入 var formData = new FormData(); //注入 name=file var files = $("#attachmentInputs2 input[type='file']"); for (var i = 0; i < files[0].files.length; i++) { formData.append("attachment", files[0].files[i]); } //注入name=text formData.append("applyId", "123456"); console.log(formData.getAll("attachment")); //执行上传 $.ajax({ url: ctx + "/attachment/upload2", type: "post", data: formData, processData: false, contentType: false, success: function (data) { }, error: function (e) { } }); });
方式3
定义了一个隐藏的input,并将Select File按钮的click与input的click对等,点击按钮相当于点击input,弹出选择文件对话框,监听了input的change事件,将选择的file对象push到全局数组变量attachmentArray中,点击Upload时再遍历注入到formData中
效果
html
<form enctype="multipart/form-data" novalidate="novalidate"> <div> <div> <label>附件管理:</label> <div> <button type="button">Select File</button> <button type="button">Upload</button> </div> </div> <div> <label>附件上传:</label> <input type="file"/> <div> </div> </div> </div> </form>
js
//存放file对象 var attachmentArray = []; //attachment-remove $("#attachmentText3").on("click", ".attachment-remove", function (even) { //删除attachmentArray数据 attachmentArray.splice($(this).data("index"), 1); //删除html对象 $(this).prev().prev().remove(); $(this).prev().remove(); $(this).remove(); }); //Select File $("#selectFile").click(function (even) { // 获取input $("#attachmentInputs3").click(); }); //input change $("#attachmentInputs3").change(function (even) { // 获取input var fileName = $(this).val(); var file = $(this)[0].files[0]; //是否选择了文件 if (fileName) { attachmentArray.push(file); $("#attachmentText3").append("<div><p>" + fileName + "</p><i data-index='" + (attachmentArray.length - 1) + "' class=\"fa fa-times attachment-remove\"></i></div>") } }); //upload3 $("#attachmentUploadBtn3").click(function (even) { //这里只能手动注入 var formData = new FormData(); //遍历数据,手动注入formData for (var i = 0; i < attachmentArray.length; i++) { formData.append("attachment", attachmentArray[i]); } formData.append("applyId", "123456"); console.log(formData.getAll("attachment")); //执行上传 $.ajax({ url: ctx + "/attachment/upload", type: "post", data: formData, processData: false, contentType: false, success: function (data) { }, error: function (e) { } }); });
最后看一下file数据、请求头、还有振奋人心的后台成功接参图
file数据
请求头
成功接参