![](/img/trans.png)
[英]How to Upload both file and data using ajax , jquery and spring mvc
[英]How to upload multiple file in form data using jQuery, ajax, spring boot
我正在尝试在 formData 中上传两个 zip 文件。
代码看起来像这样..
我的表格
<form id="fileForm"> <input type="file" name="file" id="fileOne" /> <input type="file" name="file" id="fileTwo" /> <button id="btnUpload" type="button">Upload file</button> </form>
jQuery + ajax
$(document).ready(function() { var imgContainer = $('#imgContainer'); $('#btnUpload').click(function() { var formData = new FormData(); $.each($("input[type=file]"), function(i, obj) { $.each(obj.files, function(j, file) { formData.append('file[' + j + ']', file); console.log(file); }) }); //Ajax call $.ajax({ url: 'myUrl', type: "POST", data: formData, enctype: 'multipart/form-data', processData: false, contentType: false }).done(function(data) { imgContainer.html(''); var img = '<img src="data:' + data.contenttype + ';base64,' + data.base64 + '"/>'; imgContainer.append(img); }).fail(function(jqXHR, textStatus) { //alert(jqXHR.responseText); console.log('File upload failed ...'); }); }); });
我的问题是,当我在控制器中收到文件时,我只得到一个文件。
这是我在fileMap中得到的, 一个数组的值为另一个数组为空。
我的控制器
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST, produces = { "application/json" }) @ResponseBody public String uploadFile(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception { Map < String, MultipartFile > filesMap = new HashMap < String, MultipartFile > (); filesMap = request.getFileMap(); System.out.println("filesMap :" + filesMap); return = "hello"; }
谁能帮我调试代码。 我在哪里做错了。
然而,一个老问题,我想回答:代码很好,但是你需要使用外循环的索引,因为内循环有一个项目,因此键总是枚举为 0,覆盖数组中的前一个文件,即替换j 索引与 i :
formData.append('file[' + i + ']', file);
全文摘录:
$.each($("input[type=file]"), function(i, obj) {
$.each(obj.files, function(j, file) {
formData.append('file[' + i + ']', file); //replace j index here with i
console.log(file);
})
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.