form表单多文件上传

时间:2022-11-22 13:27:38

背景

在项目开发中,经常会遇到上传图片的情况。例如,实名认证时上传身份证正反面图片,这时就会用到form表单多文件上传。本文提供两种方式:form表单直接提交和ajax提交

实现

form表单直接提交

<form enctype="multipart/form-data" action="addActivity" method="post" role="form" class="form-horizontal validate" novalidate="novalidate">
<div class="form-group">
<label class="col-sm-3 control-label">正面图</label>
<div class="col-sm-5">
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="fileinput-new thumbnail" data-trigger="fileinput">
<img src="http://placehold.it/200x150" alt="...">
</div>
<div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px"></div>
<div>
<span class="btn btn-white btn-file">
<span class="fileinput-new">选择图片</span>
<span class="fileinput-exists">修改</span>
<input type="file" name="frontPic" accept="image/*">
</span>
<a href="#" class="btn btn-orange fileinput-exists" data-dismiss="fileinput">移除</a>
</div>
</div>

</div>
</div>

<div class="form-group">
<label class="col-sm-3 control-label">反面图</label>
<div class="col-sm-5">
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="fileinput-new thumbnail" data-trigger="fileinput">
<img src="http://placehold.it/200x150" alt="...">
</div>
<div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px"></div>
<div>
<span class="btn btn-white btn-file">
<span class="fileinput-new">选择图片</span>
<span class="fileinput-exists">修改</span>
<input type="file" name="contraryPic" accept="image/*">
</span>
<a href="#" class="btn btn-orange fileinput-exists" data-dismiss="fileinput">移除</a>
</div>
</div>

</div>
</div>

<div class="form-group">
<div class="col-sm-offset-3 col-sm-5">
<button id="submit" type="submit" class="btn btn-green btn-default">保存</button>
<button id="cancel" type="submit" class="btn btn-green btn-default" >取消 </button>
</div>
</div>
<input type="hidden" name="submitType" />
</form>

这里需要注意的是form标签中属性enctype=”multipart/form-data”

ajax提交

<form id="uploadForm" method="post" enctype="multipart/form-data" >

.....

<input type="button" value="提交" id="btnImportOK">

</form>

<script src="../../partner/libs/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btnImportOK").click(function () {

var formData = new FormData($("#uploadForm")[0]);
console.log(formData)
$.ajax({
type: "POST",
data: formData,
url: "/picture/authentication",
contentType: false,
processData: false,
}).success(function (data) {

})
});
});

</script>

ajax提交时需要用到jquery中的FormData数据类型。

spring boot 后端代码

@RequestMapping(value = "/authentication", method = RequestMethod.POST)
public ResponseEntity authentication(@RequestParam(value = "frontPic", required = false) MultipartFile frontPic,
@RequestParam(value = "contraryPic", required = false) MultipartFile contraryPic,
HttpServletRequest request) {

.......

}