现在我有以下控制器方法:
@ModelAttribute("multipartFileWrapper")
public MultipartFileWrapper createEmployeeModel() {
return new MultipartFileWrapper();
}
public ResponseEntity<String> handleFileUpload(@Validated MultipartFileWrapper file, BindingResult result, Principal principal, HttpSession session) {
ResponseEntity<String> responseEntity;
if (result.hasErrors()) {
....
以及用于验证的bean包装器:
@Component
public class MultipartFileWrapper {
@Extensions(imageFormats = {".jpg",".png",".gif",".bmp"}, videoFormats = {".mp4"})
MultipartFile multipartFile;
public MultipartFile getMultipartFile() {
return multipartFile;
}
public void setMultipartFile(MultipartFile multipartFile) {
this.multipartFile = multipartFile;
}
}
扩展注释声明:
@Documented
@Retention(RUNTIME)
@Constraint(validatedBy = {ExtensionValidator.class})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
public @interface Extensions {
String message() default "file format is not acceptable";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
/**
* Specify accepted content types.
*
* @return accepted extensions
*/
String[] imageFormats();
String[] videoFormats();
}
和验证者:
public class ExtensionValidator implements ConstraintValidator<Extensions, MultipartFile> {
private String[] acceptedExtensions;
@Override
public void initialize(Extensions extensions) {
//logic
}
@Override
public boolean isValid(MultipartFile value, ConstraintValidatorContext context) {
//logic
}
}
并遵循jsp:
<form:form method="POST" action="uploadImage" enctype="multipart/form-data" id="imageUploadForm" commandName="multipartFileWrapper" >
....
</form:form>
现在我需要验证使用ajax发送的文件。
ajax电话:
$(".file").on("change", function() {
var data = $(this).attr('data');
if (typeof data !== 'undefined' && data !== false) {
var image=this.files[0];
var terminalId=data.replace("file", "");
var postData = new FormData();
postData.append('image',image);
postData.append('terminalId',terminalId);
$("div[data='errors"+terminalId+"']").hide();
$.ajax({
url: "<c:url value='/owner/terminals/uploadImage'/>",
type: 'POST',
dataType: 'json',
processData: false,
contentType: false,
data: postData
})
.success(function(data) {
...
})
.fail(function() {
...
});
}
});
我该怎么做?是否可以重用我当前的代码?