文章目录
多文件上传
实习遇到个需求,需要多文件上传和删除,还有回显的需求。
html写法:如果有需要回显的文件,则显示,用checkbox来存储需要回显文件的id,方便提交多个,在显示页面将checkbox隐藏即可。每次点击添加附件按钮,都会显示一个【选择文件】按钮。
<form id="editForm" action="/save" method="post" enctype="multipart/form-data">
<div>
<input type="button" id="showAttach" value="添加附件" />
<!--回显已上传文件-->
<ol th:if="${fileList != null}" th:each="file : ${fileList}">
<li>
<a href="javascript:void (0)" th:text="${file.name}"></a>
<input type="button" class="ddBtn btnRed removeAttach" value="移除"/>
<!--checkbox用Jquery隐藏即可-->
<input class="commonInput checkbox" type="checkbox" name="uploadedFileList" checked th:value="${file.id}" >
</li>
</ol>
<!--上传文件-->
<ol id="fileList"></ol>
</div>
</form>
js写法,基于jQuery
$(document).ready(function(){
$(".checkbox").hide();
$(document).delegate("#showAttach","click",function add() {
$("#fileList").append("<li >" +
"<input class='fileInput' name='attach' type=\"file\" />" +
"</li>");
});
$(document).delegate(".fileInput","change",function () {
var $this = $(this);
var id=$.uuid();
$(this).parent().attr("dataid",id);
var fullPath = $this.val();
var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
var filename = fullPath.substring(startIndex);
if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
filename = filename.substring(1);
$(this).parent().append("<a href=\"javascript:void (0)\">"+filename+"</a><input type=\"button\" class=\"ddBtn btnRed removeAttach\" value=\"移除\"/>")
}
console.log($(this).val());
$(this).hide();
});
$(document).delegate(".removeAttach","click",function () {
var $parent=$(this).parent();
$parent.remove();
});
});
controller写法,接受回显并编辑后的文件信息用String[] uploadedFileList
,也就是隐藏了的checkbox
的内容, 即可 对其操作。
这时候uploadedFileList
存储的就是之前上传 并且 被保留下来的文件。
/**
*保存
*/
@PostMapping("/save")
@ResponseBody
public ApiResult<Boolean> Save(String[] uploadedFileList
,@RequestParam(value = "attach",required = false) MultipartFile[] myfiles
, PolicyInfoVO policyInfoVO
) {
//do something
return "hello";
}
祝你好运!