在Spring Boot App中使用Jquery和FormData提交表单字段并将文件上传到Spring MVC控制器

时间:2022-08-24 21:46:45

I am unable to use Jquery and FormData to submit form fields and uploaded File to Spring MVC Controller in Spring Boot App.

我无法使用Jquery和FormData在Spring Boot App中提交表单字段并上传文件到Spring MVC控制器。

I keep getting this exception "The current request is not a multipart request" on the controller side.

我一直得到这个异常,“当前请求在控制器端不是一个多部分请求”。

My Setup.

我的设置。

I have a regular Spring Boot Webapp

我有一个普通的Spring Boot Webapp

This is my spring boot version :

这是我的spring引导版本:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.7.RELEASE</version>
</parent>

My Ajax form submit looks like this :

我的Ajax表单提交如下:

var entityJson = form2js("my-form-id",null,false); // js library to get json from form
var entityJsonStr = JSON.stringify(entityJson);

var formData = new FormData();
formData.append("data", entityJsonStr); // the entered data as JSON


// append files, if there are any
$.each($("#my-form-id").find("input[type='file']"), function(i, tag) {
    $.each($(tag)[0].files, function(i, file) {
       formData.append(tag.name, file);
    });
});

$.ajax({
    url:     theUrl,
    type:    'POST',
    headers: {'Content-Type': undefined},
    cache: false,
    processData: false,
    data:    formData,
    error: function(xhr,status,err){
        // failure handling
    },
    success: function(response){
        // success handling
    }
});

Only json submission works absolutely fine, (when I submit only entityJsonStr instead of FormData instance)

只有json提交工作得非常好(当我只提交entityJsonStr而不是FormData实例时)

On Server-side my Controller looks like this:

在服务器端,我的控制器是这样的:

@RequestMapping(value="/save", method= RequestMethod.POST, produces=APPLICATION_JSON_UTF_8)
public @ResponseBody WebResponse<MyEntity> save(
        @Valid @RequestPart(value="data") MyEntity myEntity
        ,@RequestPart(value = "image", required = false) MultipartFile image
) throws Exception {
    try {

        validateImage(image);
        saveImage(myEntity.getName() + ".jpg", image);

        shoppingCenterService.save(myEntity);
        MyEntity shoppingCenterWithOnlyId = getEmptyShoppingCenterWithId(myEntity.getId());

        return new WebResponse(true, SHOPPINGCENTER_SAVE_SUCCESS);
    } catch (DuplicacyException de) {
        return getDuplicacyResponse(de, myEntity);
    } catch(Exception e) {
        LOGGER.error("MyEntity Controller[save]", e);
        return new WebResponse(false, MYENTITY_SAVE_FAILED); // custom response
    }
}

when I not use @RequestPart and simply use @Valid @RequestBody MyEntity myEntity and don't use FormData object in javascript, i get the right json which translates to an object of MyEntity ...

当我不使用@RequestPart并且只使用@Valid @ requestmyentity MyEntity并且在javascript中不使用FormData对象时,我得到了正确的json,它可以翻译成MyEntity的对象……

I keep getting this exception :

我一直有这样的例外:

org.springframework.web.multipart.MultipartException: The current request is not a multipart request   

I have tried all following combinations, nothing works

我试过了所有的组合,都没有成功

// dataType: 'json',
// contentType: 'application/json',

headers: {'Content-Type': undefined},
cache: false,
//  contentType: null,
//  processData: false,
// enctype: 'multipart/form-data',
processData: false,
//contentType: false,
//cache: false,

// async:   true,
// cache:   false,
// global:  false,

but nothing is submitting the formdata + file properly.

但是没有任何东西正确地提交formdata +文件。

I have been trying to get this to work for a couple of days now ... I don't see what I am doing wrong.

我已经试着让它工作了几天了……我不知道我做错了什么。

If anybody has got this to work, please share a solution.

如果有人要工作,请分享一个解决方案。

Update:

更新:

After Jny's reply, I tried with

在Jny的回复之后,我尝试了。

headers: {'Content-Type': 'multipart/form-data'}

and

contentType:  'multipart/form-data'

Now I get :(

现在我得到了:(

org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

My Request Payload looks like this :

我的请求有效载荷如下:

------WebKitFormBoundaryPG92Ng6h630YkJKN
Content-Disposition: form-data; name="form_data"

{"id":"","name":"s","code":"s" 
  // ... more json
}
------WebKitFormBoundaryPG92Ng6h630YkJKN
Content-Disposition: form-data; name="image"; filename="ThumbsUp.jpg"
Content-Type: image/jpeg


------WebKitFormBoundaryPG92Ng6h630YkJKN--

1 个解决方案

#1


3  

Found the Solution !! and it works now Yippee :)

发现解决方案! !它现在可以工作了,Yippee:)

What we need to do is when we are setting the Json-string in the FormData, we need to specify the content-type that this part is json .... so the solution looks like this now :

我们需要做的是当我们设置FormData json字符串,我们需要指定这个部分的内容类型是json ....现在的解是这样的

var entityJson = form2js("my-form-id",null,false); // js library to get json from form
var entityJsonStr = JSON.stringify(entityJson);

var formData = new FormData();
formData.append("data", new Blob([entityJsonStr], {
                type : "application/json"  // ** specify that this is JSON**
            })); 


// append files, if there are any
$.each($("#my-form-id").find("input[type='file']"), function(i, tag) {
    $.each($(tag)[0].files, function(i, file) {
       formData.append(tag.name, file);
    });
});

$.ajax({
    url:     theUrl,
    type:    'POST',
    processData: false,
    contentType: false,
    cache: false,
    data:    formData,
    error: function(xhr,status,err){
        // failure handling
    },
    success: function(response){
        // success handling
    }
});

and then the controller looks the same as earlier.

控制器看起来和之前一样。

There was one more change, that I ended up doing for my entity. Since I now have this new form field as "image" which was not meant to be a property in my entity directly.

还有一个变化,我为我的实体做的。因为我现在有了这个新的表单字段“image”,它不是我实体中的一个属性。

So I asked Jackson to ignore those unmapped properties

所以我让Jackson忽略那些未映射的属性

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
// MyEntity class goes here {}

This works now and I am able to ajax submit the form with the form-data as well as the file.

现在可以工作了,我可以使用ajax提交表单数据和文件。

#1


3  

Found the Solution !! and it works now Yippee :)

发现解决方案! !它现在可以工作了,Yippee:)

What we need to do is when we are setting the Json-string in the FormData, we need to specify the content-type that this part is json .... so the solution looks like this now :

我们需要做的是当我们设置FormData json字符串,我们需要指定这个部分的内容类型是json ....现在的解是这样的

var entityJson = form2js("my-form-id",null,false); // js library to get json from form
var entityJsonStr = JSON.stringify(entityJson);

var formData = new FormData();
formData.append("data", new Blob([entityJsonStr], {
                type : "application/json"  // ** specify that this is JSON**
            })); 


// append files, if there are any
$.each($("#my-form-id").find("input[type='file']"), function(i, tag) {
    $.each($(tag)[0].files, function(i, file) {
       formData.append(tag.name, file);
    });
});

$.ajax({
    url:     theUrl,
    type:    'POST',
    processData: false,
    contentType: false,
    cache: false,
    data:    formData,
    error: function(xhr,status,err){
        // failure handling
    },
    success: function(response){
        // success handling
    }
});

and then the controller looks the same as earlier.

控制器看起来和之前一样。

There was one more change, that I ended up doing for my entity. Since I now have this new form field as "image" which was not meant to be a property in my entity directly.

还有一个变化,我为我的实体做的。因为我现在有了这个新的表单字段“image”,它不是我实体中的一个属性。

So I asked Jackson to ignore those unmapped properties

所以我让Jackson忽略那些未映射的属性

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
// MyEntity class goes here {}

This works now and I am able to ajax submit the form with the form-data as well as the file.

现在可以工作了,我可以使用ajax提交表单数据和文件。