我在Spring Boot应用程序中上传多个文件以及表单数据时遇到问题。我正在使用jQuery发布数据

时间:2019-06-23 01:13:00

标签: jquery spring-boot

我的jquery代码如下

var form = $('form#'+'wizard2');              //对数组集合中的所有输入值(不是文件!)进行序列化,以便以后可以迭代该集合。             var params = form.serializeArray();

        var files = $("#parafile");
        //Declaring new Form Data Instance  
        var formData = new FormData();
       //Looping through uploaded files collection in case there is a Multi File Upload. This also works for single i.e simply remove MULTIPLE attribute from file control in HTML.  
        for (var i = 0; i < files.length; i++) {
            formData.append(files[i].name, files[i]);
        }
      //Now Looping the parameters for all form input fields and assigning them as Name Value pairs. 
        $(params).each(function (index, element) {
            console.log(element.name +' =='+  element.value);
            formData.append(element.name, element.value);
        });

        $.ajax({
            url : '/paragliding/saveNewPackage',
            type: "POST",               
            data : JSON.stringify(formData),
            cache: false,               
            processData: false,
            contentType: false,
            enctype: 'multipart/form-data',
            cache: false,
            success : function(data) {
                swal({
                    title: "Well done!",
                    text: "You successfully completed the form wizard.",
                    type: "success"
                });
                location.reload(true);
            },

            error: function (error) { alert(error); }
        });

我的服务器端代码为

@RequestMapping(值=     {“ / saveNewPackage”},方法= RequestMethod.POST,消耗= MediaType.MULTIPART_FORM_DATA_VALUE,标题=“ Content-Type = multipart / form-data”)

public String saveParagliding(Authentication authentication, HttpServletRequest request,
                              @RequestParam ("model") String model, @RequestParam (value = "parafile[]", required = false) MultipartFile[] file)
        throws JsonParseException, JsonMappingException, IOException
{

    UserDetails userDetails = (UserDetails) authentication.getPrincipal();
    boolean isAuthenticated = userDetails.getAuthorities().stream().anyMatch(grantedAuthority -> {
        String grants = grantedAuthority.getAuthority();
        return grants.equalsIgnoreCase(UserRole.ROLE_TYPE_ADMIN.getRoleName())
                || grants.equalsIgnoreCase(UserRole.ROLE_TYPE_CAMP_PARTNER.getRoleName());
    });

    if (!isAuthenticated)
    {
        return "UnAuthorized";
    }

}

0 个答案:

没有答案