Spring Boot 2.0: Multi‑Image Upload with Real‑Time Preview
This guide demonstrates how to build a Spring Boot 2.0 backend that accepts multiple image files, returns upload success, and displays real‑time previews on the frontend using HTML, JavaScript, and Spring MVC multipart handling, along with configuration and error handling tips.
SpringBoot 2.0 Multi‑Image Upload with Preview
Company needed a merchant registration backend where merchants can upload multiple images and see them displayed after upload. This article records the steps and key points.
Upload
Controller code using Spring MVC and MultipartFile array. Parameter name must match the name.
@RequestMapping("/pic")
@ResponseBody
public ResponseEntity<String> pic(MultipartFile[] pictures) throws Exception {
ResponseEntity<String> responseEntity = new ResponseEntity<>();
long count = Arrays.asList(pictures).stream()
.map(MultipartFile::getOriginalFilename)
.filter(String::isEmpty).count();
if (count == pictures.length) {
responseEntity.setCode(ResponseEntity.ERROR);
throw new NullOrEmptyException("图片不能同时为空");
}
responseEntity.setCode(ResponseEntity.OK);
responseEntity.setMessage("上传成功");
return responseEntity;
}Frontend HTML
The name must correspond to the controller parameter.
<div class="container">
<div class="avatar-upload">
<div class="avatar-edit">
<input type="file" name="pictures" id="imageOne" accept=".png, .jpg, .jpeg"/>
<label for="imageOne"></label>
</div>
<div class="avatar-preview">
<div id="imageOnePreview" style="background-image: url(http://...);"></div>
</div>
</div>
</div>JavaScript for Preview
function readURLOne(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imageOnePreview').css('background-image', 'url(' + e.target.result + ')');
$('#imageOnePreview').hide();
$('#imageOnePreview').fadeIn(650);
};
reader.readAsDataURL(input.files[0]);
}
}
$("#imageOne").change(function () {
readURLOne(this);
});JavaScript for Upload
function getUpload() {
var formData = new FormData($("#picForm")[0]);
$.ajax({
url: '/pic',
type: 'POST',
dataType: "json",
data: formData,
processData: false,
contentType: false,
success: function (data) {
window.confirm(data.message);
window.location.reload();
},
error: function (res) {
alert("失败");
}
});
}Configuration
Default max file size is 1 MB. To increase, set properties in application.yml:
spring:
servlet:
multipart:
enabled: true
max-file-size: 20MB
max-request-size: 20MBAdditional multipart properties:
spring.servlet.multipart.enabled=true
spring.servlet.multipart.file-size-threshold=0B
spring.servlet.multipart.location=
spring.servlet.multipart.max-file-size=1MB
spring.servlet.multipart.max-request-size=10MB
spring.servlet.multipart.resolve-lazily=falseException Handling
Use Spring Boot’s global exception handling with @ControllerAdvice:
@ControllerAdvice
@Slf4j
public class CommonExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(NullOrEmptyException.class)
@ResponseBody
public ResponseEntity<String> nullOrEmptyExceptionHandler(HttpServletRequest request,
NullOrEmptyException exception) {
log.info("nullOrEmptyExceptionHandler");
return handleErrorInfo(request, exception.getMessage());
}
@ExceptionHandler(Exception.class)
@ResponseBody
public ResponseEntity<String> defaultErrorHandler(HttpServletRequest request,
Exception exception) {
log.info("defaultErrorHandler");
return handleErrorInfo(request, exception.getMessage());
}
private ResponseEntity<String> handleErrorInfo(HttpServletRequest request, String message) {
ResponseEntity<String> responseEntity = new ResponseEntity<>();
responseEntity.setMessage(message);
responseEntity.setCode(ResponseEntity.ERROR);
responseEntity.setData(message);
responseEntity.setUrl(request.getRequestURL().toString());
return responseEntity;
}
}Common Pitfalls
If the controller returns a view name, do not add @ResponseBody, otherwise the view name will be serialized as JSON.
Ensure the frontend parameter name matches the backend parameter name; otherwise a 405 error may occur.
When using Lombok in IDEA, enable annotation processing in the IDE settings.
Result screenshots:
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
