ax将Multipart文件从Jquery发送到Spring控制

ax将Multipart文件从Jquery发送到Spring控制

本文介绍了无法使用ajax将Multipart文件从Jquery发送到Spring控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将jquery中的Multipart文件发送到spring控制器.

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

以下是我得到的错误

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]

以下是用户界面代码

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

    </div>

我正在通过ajax呼叫发送

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

我的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());

出现该错误的原因是什么?我该如何解决?

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

推荐答案

尝试下面的代码,并在ajax代码中进行一些更改.在代码中添加以下参数.

processData:否,
contentType:否,

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

processData: false,
contentType: false,

并在Ajax启动之前添加 var formData = new FormData($(#formID")[0]); 行.

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

这篇关于无法使用ajax将Multipart文件从Jquery发送到Spring控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 06:37