2

I have a program that has a functionality to upload a file and then validate if it's name format is correct and save it to db.

In my main controller I am using @InitBinder for validation.

@InitBinder("uploadFileForm")
    protected void initBinderUploadForm(WebDataBinder binder) {
        binder.setValidator(fileNameFormatValidator);
    }

In my validator method I am using this code snippet:

static void validateFileName(String fileUploadKey, MultipartFile file, Errors errors) {
        Matcher validFilenameMatcher = VALID_FILE_NAME.matcher(file.getOriginalFilename());
        if (!validFilenameMatcher.matches()) {
            errors.rejectValue(fileUploadKey, null, null, SOME_REGEX);
        }
    }

What I want to do is, I want to format file name (like replacing some characters in file name) and then use validator class. Thus I need to change file name before the validation.

How can I achieve editing file name before validating the format with @InitBinder?

Edit: Noone answers? Or the question isn't clear ?

Chris Garsonn
  • 717
  • 2
  • 18
  • 32

1 Answers1

1

Why not use WebDataBinder's addCustomFormatter like you did for adding a validator ?

@InitBinder("uploadFileForm")
protected void initBinderUploadForm(WebDataBinder binder) {
    binder.addCustomFormatter(fileNameFormatter); 
    binder.setValidator(fileNameFormatValidator);
}
Dovmo
  • 8,121
  • 3
  • 30
  • 44
amineT
  • 76
  • 5
  • nice. but if I use addCustomFormatter then how can I edit format name ? I mean: for validation it is not changing anything just check and throw exception, where as if I do some change like name = name + '2' how can I change the file name like a static variable or etc.. – Chris Garsonn Jan 10 '19 at 15:09
  • Sorry for the late response. Create your own fileFormatter with a Multipart generic type, that way you will override the parse method and return a new file with the desired name. Didn't test it on files before only on domain object so let me know if it works for you – amineT Jan 11 '19 at 07:55