参考下面的代码你可以上传多个文件,工作正常
<form method="POST" enctype="multipart/form-data"
id="fileUploadForm">
<div class="controls">
<div class="entry input-group col-xs-3">
<input class="btn btn-primary" name="files" type="file">
<span class="input-group-btn">
<button class="btn btn-success btn-add" type="button">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</div>
</form>
JS
$(document).ready(function() {
$("#btnSubmit").click(function(event) {
// stop submit the form, we will post it manually.
event.preventDefault();
fire_ajax_submit();
});
});
function fire_ajax_submit() {
// Get form
var form = $('#fileUploadForm')[0];
var data = new FormData(form);
data.append("CustomField", "This is some extra data, testing");
// $("#btnSubmit").prop("disabled", true);
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
$.ajax({
method : "POST",
enctype : 'multipart/form-data',
url : "lotConfig/lotImage",
data : data,
// http://api.jquery.com/jQuery.ajax/
// https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
processData : false, // prevent jQuery from automatically
// transforming the data into a query string
contentType : false,
cache : false,
timeout : 600000,
success : function(data) {
jQuery('#lotImageget').html('');
getAllLotiamges();
$('#updateImage').modal('hide');
/*
* $("#result").text(data); console.log("SUCCESS : ", data);
* $("#btnSubmit").prop("disabled", false);
*/
},
error : function(e) {
$("#result").text(e.responseText);
console.log("ERROR : ", e);
// $("#btnSubmit").prop("disabled", false);
}
});
}
弹簧控制器
@PostMapping(value = "/lotImage")
public ResponseEntity<String> updateLotImage(
@RequestParam("files") MultipartFile[] files,
RedirectAttributes redirectAttributes, HttpSession session)
throws IOException {
logger.info("--got request to update Lot Image--");
StringJoiner sj = new StringJoiner(" , ");
for (MultipartFile file : files) {
if (file.isEmpty()) {
continue; // next pls
}
try {
byte[] bytes = file.getBytes();
Properties prop = new Properties();
String resourceName = "app.properties";
ClassLoader loader = Thread.currentThread()
.getContextClassLoader();
InputStream resourceStream = loader
.getResourceAsStream(resourceName);
try {
prop.load(resourceStream);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String image_path = prop.getProperty("LOT_DESTINATION_IMG");
Path path = Paths.get(image_path
+ file.getOriginalFilename());
Files.write(path, bytes);
sj.add(file.getOriginalFilename());
} catch (IOException e) {
e.printStackTrace();
}
}
logger.info("--Image updated--");
return new ResponseEntity<String>("Success", HttpStatus.OK);
}