这里以上传多组单体图片为例
CSS部分:
<form id="upBox" class="upload_form" action="" method="post" enctype="multipart/form-data">
<div>
<input type="file" name="image[]" data-id="1" title="请选择图片" id="file1" class="filePicUpload" accept="image/png,image/jpg,image/gif,image/JPEG" />
<input type="file" name="image[]" data-id="2" title="请选择图片" id="file2" class="filePicUpload" accept="image/png,image/jpg,image/gif,image/JPEG" />
<input type="file" name="image[]" data-id="3" title="请选择图片" id="file3" class="filePicUpload" accept="image/png,image/jpg,image/gif,image/JPEG" />
<input type="file" name="image[]" data-id="4" title="请选择图片" id="file4" class="filePicUpload" accept="image/png,image/jpg,image/gif,image/JPEG" />
<input type="file" name="image[]" data-id="5" title="请选择图片" id="file5" class="filePicUpload" accept="image/png,image/jpg,image/gif,image/JPEG" />
<input type="file" name="image[]" data-id="6" title="请选择图片" id="file6" class="filePicUpload" accept="image/png,image/jpg,image/gif,image/JPEG" />
</div>
</form>
<input type="button" value="保 存" onclick="uploadPicFile()">
JS部分:
/**
* 上传图片
* 上传文件一定要加(contentType: false,processData: false),否则会报错噢
*/
function uploadPicFile(){
var formData = new FormData();
var file1 = $('#file1')[0].files[0];
if(file1 != null){
formData.append('uploadFile', file1);
}
var file2 = $('#file2')[0].files[0];
if(file2 != null){
formData.append('uploadFile', file2);
}
var file3 = $('#file3')[0].files[0];
if(file3 != null){
formData.append('uploadFile', file3);
}
var file4 = $('#file4')[0].files[0];
if(file4 != null){
formData.append('uploadFile', file4);
}
var file5 = $('#file5')[0].files[0];
if(file5 != null){
formData.append('uploadFile', file5);
}
var file6 = $('#file6')[0].files[0];
if(file6 != null){
formData.append('uploadFile', file6);
}
formData.append('id', '123456789');
$.ajax({
type: "post",
url: "uploadPicFile",
data: formData,
contentType: false,
processData: false,
success: function (data) {
if (data.errStat !== 0) {
layer.alert(data.data, {
icon: 2
});
return;
}
},
error: function (data) {
layer.alert(data.errMsg, {
icon: 2
});
}
});
}
JAVA后台部分:
> Result 是我自定义的返回值,可以使用Map等代替
/**
* @Description: 上传多组图片方法
* @Param: [uploadFile, id]
* @return: com.fmz.demo.core.entity.Result
* @Author: fmz
* @Date: 2021/9/14
*/
@PostMapping(value = "/uploadPicFile")
@ResponseBody
public Result uploadPicFile(@RequestParam("uploadFile") MultipartFile[] uploadFile
,@RequestParam("id") String id) {
if(uploadFile != null && uploadFile.length > 0 && !StringUtils.isEmpty(id)){
return Result.ok();
}
return Result.fail("文件为空");
}