These two days, the company needs to make a business registration background function, which requires businesses to upload a number of pictures and echo. Since I haven't done anything in this area before, this article is used to record some knowledge points for subsequent review.
upload
Controller's code is very simple, because it uses the Spring MVC framework, so it can be answered directly with MultipartFile. Because it is multi-image upload, it is connected by an array. It should be noted here that the parameter name should correspond to the name value in <input>.
@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("Pictures cannot be empty at the same time"); } responseEntity.setCode(ResponseEntity.OK); responseEntity.setMessage("Upload Success"); return responseEntity; }
The code for the front-end page, where the name value corresponds to the parameter name of the Controller
<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://ww3.sinaimg.cn/large/006tNc79ly1g556ca7ovqj30ak09mta2.jpg);"> </div> </div> </div> </div>
js code echo
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); });
js code upload
function getUpload(){ //Get all the attribute key s in the form as name values 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("fail"); }) }); }
Effect Show
The initial page is as follows
After uploading the picture, it will be echoed as follows
After clicking submit, you can upload the picture to the background.
Configure the properties of uploaded pictures
By default, only images below 1MB are allowed to be uploaded, if the upload size is to be set. Then you need to configure it in the configuration file as follows
spring: servlet: multipart: enabled: true max-file-size: 20MB max-request-size: 20MB
There are the following configurations for files
spring.servlet.multipart.enabled=true # Does it support multi-file upload? spring.servlet.multipart.file-size-threshold=0B # Threshold of File Writing to Disk spring.servlet.multipart.location= # Save address of uploaded file spring.servlet.multipart.max-file-size=1MB # Maximum upload file spring.servlet.multipart.max-request-size=10MB # Maximum value of request spring.servlet.multipart.resolve-lazily=false # Whether to delay parsing multiple requests when accessing files or parameters
exception handling
Exception handling uses the global exception handling mechanism provided by Springboot. Just add the @Controller Advice annotation to the class. Adding @ExceptionHandler (the exception class you want to intercept) to the method will intercept all Controller exceptions. If you want to intercept a specific Controller, you only need to @Controller Advice (base Package Classes = Controller you want to intercept)
@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(value = 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; } }
Pits encountered
-
If the return value is the file name of the template file, then neither the class nor the method can be annotated with @ResponseBody, because if it is added, it will be parsed into a Json string to return.
-
Note that the parameter names passed by the front end correspond to those received by the back end one by one. Otherwise 405 errors will be reported.
-
Developing with IDEA using lombok requires checking Enable annotation processing in Annotation Processors