Unable to send the Multipart file from Jquery to s

2019-08-20 07:34发布

I am trying to send the Multipart file from jquery to spring controller.

Following is the error I am getting

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]

Following is the UI code

    <div class="form-group"> 
                <form:input type="file" id="addrDocImage" path="addrDocImage" name="addrDocImage"/>

    </div>

I am sending through ajax call

   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){
                    }
                });
         }); 
        }            
    });
}

My DTO is

 public class AddressDTO implements Serializable {

 private static final long serialVersionUID = 2931368070275666084L;
 private long addrId;
 private long partyId;
 private String locationName;
 private MultipartFile addrDocImage;
 ''''''
 }

My controller code is

    @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());

What's the reason for getting that error.How can i solve it?

1条回答
SAY GOODBYE
2楼-- · 2019-08-20 08:16

Try below code and make few changes in ajax code. Add below parameters in your code.

processData: false,
contentType: false,

And add var formData = new FormData($("#formID")[0]); line before ajax starts.

Or Check below code and make changes according to you code.

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) {
                }
            });
        });
    }
});

查看更多
登录 后发表回答