前端HTML代码
<div class="add_div">
<span class="add choose">上传寄件码截图</span>
<input type="file" name="" id="choose-file" style="opacity: 0" multiple/>
<ul class="file-list " id="usrc">
</ul>
</div>
前端Javascript代码
function addExpress() {
var v1 = $("ul").find('li:nth-child(1)').attr('value')
console.log("图片路径1" + v1);
var v2 = $("ul").find('li:nth-child(2)').attr('value');
console.log("图片路径2" + v2);
var v3 = $("ul").find('li:nth-child(3)').attr('value');
console.log("图片路径3" + v3);
let formData = new FormData();
let image = $("#choose-file")[0].files;
for (let item of image) {
formData.append("files", item);
}
var sends = JSON.stringify({
"picture1": v1,
"picture2": v2,
"picture3": v3,
});
formData.append('sends', new Blob([sends], {type: "application/json"}))
console.log("图片数组" + formData);
$.ajax({
url: "${pageContext.request.contextPath}/sendAdd",
method: "post",
contentType: false,
processData: false,
data: formData,
dataType: "json",
}
}
后端数据处理
@RequestMapping(value = "/sendAdd", method = RequestMethod.POST)
public void sendAdd(HttpServletResponse response,
@RequestPart(value = "files") MultipartFile[] files,
@RequestPart("sends") Send sends) throws IOException {
Send send = new Send();
String picture1 = sends.getPicture1();
String picture2 = sends.getPicture2();
String picture3 = sends.getPicture3();
send.setPicture1(picture1);
send.setPicture2(picture2);
send.setPicture3(picture3);
if (files.length > 0) {
for (int i = 0; i < files.length; i++) {
String originalFileName = files[i].getOriginalFilename();
UUID uuid = UUID.randomUUID();
long leastSignificantBits = uuid.getLeastSignificantBits();
long fileSize = files[i].getSize();
String tempPath = "F:" + File.separator + "ParadeMan" + File.separator + "image";
File savePathDir = new File(tempPath);
if (!savePathDir.exists()) {
savePathDir.mkdirs();
}
String fil = leastSignificantBits + originalFileName;
log.info("图片信息" + fil);
files[i].transferTo(new File(tempPath, fil));
}
}
}