最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot?上傳文件判空以及格式檢驗(yàn)流程

 更新時(shí)間:2022年03月24日 11:03:52   作者:?吾?非?水  
這篇文章主要介紹了SpringBoot?上傳文件判空以及格式檢驗(yàn)流程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

基于jsr303 通過自定義注解實(shí)現(xiàn),實(shí)現(xiàn)思路:

存在一些瑕疵,后續(xù)補(bǔ)充完善。

加入依賴

部分版本已不默認(rèn)自動(dòng)引入該依賴,選擇手動(dòng)引入

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

創(chuàng)建自定義注解以及實(shí)現(xiàn)類

目錄結(jié)構(gòu):

  • FileNotEmpty 自定義注解
  • FileNotEmptyValidator 單文件校驗(yàn)
  • FilesNotEmptyValidator 多文件校驗(yàn)
/**
 * jsr303 文件格式校驗(yàn)注解
 *
 * @author maofs
 * @version 1.0
 * @date 2021 -11-29 10:16:03
 */
@Documented
@Constraint(
        validatedBy = {FileNotEmptyValidator.class, FilesNotEmptyValidator.class}
)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
public @interface FileNotEmpty {
    /**
     * Message string.
     *
     * @return the string
     */
    String message() default "文件格式不正確";
    /**
     * 校驗(yàn)組
     *
     * @return the class [ ]
     */
    Class<?>[] groups() default {};
    /**
     * Payload class [ ].
     *
     * @return the class [ ]
     */
    Class<? extends Payload>[] payload() default {};
    /**
     * 需要校驗(yàn)的格式數(shù)組
     *
     * @return the string [ ]
     */
    String[] format() default {};
    /**
     * 是否必填 為false時(shí)文件為空則不校驗(yàn)格式,不為空則校驗(yàn)格式
     * 為true時(shí)文件不能為空且需要驗(yàn)證格式
     *
     * @return the boolean
     */
    boolean required() default true;
/**
 * 單文件校驗(yàn)
 *
 * @author maofs
 * @version 1.0
 * @date 2021 -11-29 10:16:03
 */
public class FileNotEmptyValidator implements ConstraintValidator<FileNotEmpty, MultipartFile> {
    private Set<String> formatSet = new HashSet<>();
    private boolean required;
    @Override
    public void initialize(FileNotEmpty constraintAnnotation) {
        String[] format = constraintAnnotation.format();
        this.formatSet = new HashSet<>(Arrays.asList(format));
        this.required = constraintAnnotation.required();
    }
    @Override
    public boolean isValid(MultipartFile multipartFile, ConstraintValidatorContext constraintValidatorContext) {
        if (multipartFile == null || multipartFile.isEmpty()) {
            return !required;
        }
        String originalFilename = multipartFile.getOriginalFilename();
        assert originalFilename != null;
        String type = originalFilename.substring(originalFilename.lastIndexOf('.') + 1).toLowerCase();
        if (!formatSet.isEmpty()) {
            return formatSet.contains(type);
        }
        return true;
    }
}
/**
 *  多文件校驗(yàn)
 *
 * @author maofs
 * @version 1.0
 * @date 2021 -11-29 10:16:03
 */
public class FilesNotEmptyValidator implements ConstraintValidator<FileNotEmpty, MultipartFile[]> {
    private Set<String> formatSet = new HashSet<>();
    private boolean required;
    @Override
    public void initialize(FileNotEmpty constraintAnnotation) {
        String[] format = constraintAnnotation.format();
        this.formatSet = new HashSet<>(Arrays.asList(format));
        this.required = constraintAnnotation.required();
    }
    @Override
    public boolean isValid(MultipartFile[] multipartFiles, ConstraintValidatorContext constraintValidatorContext) {
        if (multipartFiles == null || multipartFiles.length == 0) {
            return !required;
        }
        for (MultipartFile file : multipartFiles) {
            String originalFilename = file.getOriginalFilename();
            assert originalFilename != null;
            String type = originalFilename.substring(originalFilename.lastIndexOf('.') + 1).toLowerCase();
            if (formatSet.isEmpty() || !formatSet.contains(type)) {
                return false;
            }
        }
        return true;
    }
}

全局異常處理

/**
 * 統(tǒng)一異常處理
 *
 * @author maofs
 * @version 1.0
 * @date 2021 -11-29 10:16:03
 */
@ControllerAdvice
public class ExceptionHandle {
    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
       
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result<String> handle(Exception e) {
        logger.error(e.getMessage());
        StringBuilder stringBuilder = new StringBuilder();             
            //jsr303異常
          if (e instanceof ConstraintViolationException) {
            ConstraintViolationException ex = (ConstraintViolationException)e;
            Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
            for (ConstraintViolation<?> constraintViolation : constraintViolations) {
                stringBuilder.append(constraintViolation.getMessageTemplate());
            }
        } else if (e instanceof BindException) {
            BindException bindException = (BindException)e;
            stringBuilder.append(bindException.getFieldErrors()
                .stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(",")));
        } else {
            stringBuilder.append("未知錯(cuò)誤:").append("請(qǐng)聯(lián)系后臺(tái)運(yùn)維人員檢查處理!");           
        }
        return  ResultUtil.fail(stringBuilder.toString());
    }    
}

使用示例

/**
 * 文件上傳示例接口
 *
 * @author maofs
 * @version 1.0
 * @date 2021 -11-19 16:08:26
 */
@RestController
@Validated
@RequestMapping("/annex")
public class AnnexController {
 @Resource
 private IAnnexService annexService;
   /**
     * 文件上傳示例1
     *
     * @param uploadDTO the upload dto
     * @return the result
     */
    @PostMapping(value = "/upload1")
    public Result<String> upload(@Valid AnnexUploadDTO uploadDTO) {
        return Boolean.TRUE.equals(annexService.upload(uploadDTO)) ? ResultUtil.success() : ResultUtil.fail();        
    }
    
   /**
     * 文件上傳示例2
     *
     * @param number      項(xiàng)目編號(hào)
     * @param pictureFile 圖片文件
     * @param annexFile   附件文件
     * @return result result
     */
    @PostMapping(value = "/upload2")
    public Result<String> upload(@NotBlank(@FileNotEmpty(format = {"png", "jpg"}, message = "圖片為png/jpg格式", required = false)
                                         MultipartFile pictureFile, @FileNotEmpty(format = {"doc", "docx", "xls", "xlsx"}, message = "附件為doc/docx/xls/xlsx格式", required = false)
                                         MultipartFile annexFile) {       
        return Boolean.TRUE.equals(annexService.upload( pictureFile, annexFile)) ? ResultUtil.success() : ResultUtil.fail();
    }
    
	@Data
	static class AnnexUploadDTO{ 
	    @FileNotEmpty(format = {"pdf","doc","zip"}, message = "文件為pdf/doc/zip格式")
	    private MultipartFile[] file;
    }
}

結(jié)果展示

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

浦城县| 鹤山市| 滨海县| 鹤山市| 辽中县| 焦作市| 昂仁县| 禹城市| 云阳县| 资中县| 奎屯市| 宝清县| 江永县| 韶关市| 新蔡县| 都安| 曲阳县| 榆林市| 绥芬河市| 牡丹江市| 科技| 南岸区| 双牌县| 左权县| 龙泉市| 正镶白旗| 定日县| 乌兰察布市| 庄河市| 江门市| 沈阳市| 公主岭市| 同德县| 崇明县| 桐梓县| 江华| 社会| 广平县| 太保市| 扶风县| 边坝县|