问题
Please help me to resolve my problem! I have bootstrap fileinput, files are included:
<link href="/assets/css/fileinput/fileinput.css" rel="stylesheet" type="text/css">
<link href="/assets/css/fileinput/fileinput-rtl.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="/assets/js/fileinput/fileinput.js"></script>
<script type="text/javascript" src="/assets/js/plugins/fileinput/piexif.js"></script>
<script type="text/javascript" src="/assets/js/plugins/fileinput/sortable.js"></script>
<script type="text/javascript" src="/assets/js/plugins/fileinput/purify.js"></script>
Also I have a macros for fileInput:
<#macro fileInputBind path required=false fileMask="">
<@spring.bind path/>
<div class="form-group">
<@label path required/>
<#assign replacedPath = path?replace(".", "-") />
<#assign fileInputId = "${replacedPath}" />
<div class="col-md-12">
<input id="${fileInputId}" name="${spring.status.expression}" type="file" class="form-control file-styled"
accept="${fileMask}">
</div>
</div>
</#macro>
Here is my ftl element:
<@form.fileInputBind "incidentRovdCreateForm.attachment"/>
And variable in my form to handle this field:
private MultipartFile attachment;
But when @PostMapping executed I got an error in this part:
if (bindingResult.hasErrors())
return new ModelAndView("incident-rovd/create")
.addObject("typeIncident1", incidentTypeLevel1Repository.findAll())
.addObject("typeIncident2", form.getIncidentTypeLevel1() == null ? Collections.emptyList() : incidentTypeLevel2Repository.findAllByParent(form.getIncidentTypeLevel1()))
.addObject("typeIncident3", form.getIncidentTypeLevel2() == null ? Collections.emptyList() : incidentTypeLevel3Repository.findAllByParent(form.getIncidentTypeLevel2()))
.addObject("incidentRovdCreateForm", form);
Error: Failed to convert property value of type 'java.lang.String' to required type 'org.springframework.web.multipart.MultipartFile' for property 'attachment'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'org.springframework.web.multipart.MultipartFile' for property 'attachment': no matching editors or conversion strategy found.
What problem can i have?
回答1:
I have encountered the same problem with HTML + JavaScript as the frontend. If the file property of bean is not required, following may help you:
// js
var formData = new FormData(document.getElementById("yourFormId"));
//TestBean.java
@Transient
private MultipartFile file;
This method avoids the "Cannot convert String to MultipartFile" error.
来源:https://stackoverflow.com/questions/51113029/cannot-convert-string-to-multipartfile