Spring upload form optional with optional file -
we creating profile page form optionally has profile pic on it. using spring 3.2
here form: -
<form:form id="editmember" modelattribute="memberajaxeditmodel" method="post" class="form-horizontal" enctype="multipart/form-data" > ... <form:input path="filedata" type="file"/> ... </form>
here controller method: -
@requestmapping(value = "/{id}", method = requestmethod.post) public string oneditpost(@pathvariable long id, @valid @modelattribute(memberajaxeditmodel.key) memberajaxeditmodel model, bindingresult result) throws servicerecoverableexception { .... }
here model
public class memberajaxeditmodel { ... private commonsmultipartfile filedata; ... }
it works fine if file submitted on form, there errors in bindingresult variable if form submitted without file.
here error: -
field error in object 'memberajaxeditmodel' on field 'filedata': rejected value []; codes [typemismatch.memberajaxeditmodel.filedata,typemismatch.filedata,typemismatch.org.springframework.web.multipart.commons.commonsmultipartfile,typemismatch]; arguments [org.springframework.context.support.defaultmessagesourceresolvable: codes [memberajaxeditmodel.filedata,filedata]; arguments []; default message [filedata]]; default message [failed convert property value of type 'java.lang.string' required type 'org.springframework.web.multipart.commons.commonsmultipartfile' property 'filedata'; nested exception java.lang.illegalstateexception: cannot convert value of type [java.lang.string] required type [org.springframework.web.multipart.commons.commonsmultipartfile] property 'filedata': no matching editors or conversion strategy found]
it turns out jquery form plugin sending empty string instead of spring expects - nil sent.
i solved problem using before submit remove filedata value if wasn't populated so: -
function beforesubmit(arr, $form, options){ var filedataindex = -1; $.each(arr, function(index, value) { if (value.name == "filedata"){ if (value.value.length == 0){ filedataindex = index; } } }); if (filedataindex != -1){ arr.remove(filedataindex); } }
i hope helps googlers same problem.
spring spring-mvc file-upload
No comments:
Post a Comment