jquery에서 Spring 컨트롤러로 Multipart 파일을 보내려고합니다.
다음은 내가 얻는 오류입니다.
WARN : org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Handler execution resulted in exception: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'addressDTO' on field 'addrDocImage': rejected value [590768c44b1291493657796.png]; codes [typeMismatch.addressDTO.addrDocImage,typeMismatch.addrDocImage,typeMismatch.org.springframework.web.multipart.MultipartFile,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [addressDTO.addrDocImage,addrDocImage]; arguments []; default message [addrDocImage]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'org.springframework.web.multipart.MultipartFile' for property 'addrDocImage'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.springframework.web.multipart.MultipartFile] for property 'addrDocImage': no matching editors or conversion strategy found]
다음은 UI 코드입니다.
<div class="form-group">
<form:input type="file" id="addrDocImage" path="addrDocImage" name="addrDocImage"/>
</div>
Ajax 호출을 통해 보내고 있습니다.
submitHandler: function(form) {
var addressType=$("#addressType option:selected").text();
var country=$("#country option:selected").text();
var region=$("#region option:selected").text();
var city=$("#city option:selected").text();
var addrDocImage=$("#addrDocImage option:selected").text();
var formData= new FormData();
var length = document.getElementById('addrDocImage').files.length;
if(length==0){
alert("No File Choosen");
return true;
}
if(document.getElementsByName('documentTypeId')[0].value == 0){
alert(document.getElementsByName('documentTypeId')[0].value);
alert("Please choose Document Type");
return true;
}
for (var i = 0; i < length; i++) {
var file=document.getElementById('addrDocImage').files[i];
var fileName = file.name;
var fileExtension = fileName.split('.')[fileName.split('.').length - 1].toLowerCase();
if(fileExtension == "pdf" || fileExtension == "jpeg" || fileExtension == "jpg" || fileExtension == "bmp" || fileExtension == "png" || fileExtension == "gif"){
formData.append("file", file);
}else{
alert("Please upload document of type image or pdf ");
return true;
}
}
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize()+formData,
beforeSend: function(xhr){
xhr.setRequestHeader('X-CSRF-Token', $("meta[name='_csrf']").attr("content"));
},
success: function(response) {
$('#merchantAddressCreationForm').modal('hide');
//$('#merchantAddressCreationForm').modal('toggle');
swal({
title: "",
text: response,
}, function() {
$.ajax({
type: 'GET',
url: 'addressDetails',
data : "_csrf="+$("meta[name='_csrf']").attr("content"),
success:function(data){
$(".merchant_address_data").html(data);
},
error:function(response){
}
});
});
}
});
}
내 DTO는
public class AddressDTO implements Serializable {
private static final long serialVersionUID = 2931368070275666084L;
private long addrId;
private long partyId;
private String locationName;
private MultipartFile addrDocImage;
''''''
}
내 컨트롤러 코드는
@RequestMapping(value="/createMerchantAddress", method = RequestMethod.POST )
public @ResponseBody String createMerchantAddress(@ModelAttribute("addressDTO") AddressDTO addressDTO,@AuthenticationPrincipal PNSolUser loggedUser){
addressDTO.setPartyId(loggedUser.getPartyId());
addressDTO.setCreatedBy(loggedUser.getUserId());
addressDTO.setCreatedDate(Calendar.getInstance().getTime());
오류가 발생하는 이유는 무엇이며 어떻게 해결할 수 있습니까?
아래 코드를 시도하고 ajax 코드를 약간 변경하십시오. 코드에 아래 매개 변수를 추가하십시오.
processData : false,
contentType : false,
그리고 var formData = new FormData ($ ( "# formID") [0]); ajax가 시작되기 전에 줄.
또는 아래 코드를 확인하고 코드에 따라 변경하십시오.
var formData = new FormData($(form)[0]);
$.ajax({
url: form.action,
type: form.method,
data: formData,
processData: false,
contentType: false,
beforeSend: function (xhr) {
xhr.setRequestHeader('X-CSRF-Token', $("meta[name='_csrf']").attr("content"));
},
success: function (response) {
$('#merchantAddressCreationForm').modal('hide');
//$('#merchantAddressCreationForm').modal('toggle');
swal({
title: "",
text: response,
}, function () {
$.ajax({
type: 'GET',
url: 'addressDetails',
data: "_csrf=" + $("meta[name='_csrf']").attr("content"),
success: function (data) {
$(".merchant_address_data").html(data);
},
error: function (response) {
}
});
});
}
});
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다