Spring MVC同时上传表单数据和文件

    在Spring 4.0.2版本提供的restful服务中,可以通过注解@RequestPart来同时上传格式化的XML/JSON数据和文件。

    后端Controller包含Multipart和JSON的请求写法如下:

@RequestMapping(value = "/executesampleservice", method = RequestMethod.POST,
    consumes = {"multipart/form-data"})
@ResponseBody
public boolean executeSampleService(
        @RequestPart("properties")  ConnectionProperties properties,
        @RequestPart("file")  MultipartFile file) {
    return projectService.executeSampleService(properties, file);
}

前端写法:

(1)创建一个FormData对象;
(2)使用如下方式追加表单数据到FormData对象:
      (a)如果文件已经上传,使用文件类型的输入参数,formData.append("file", document.forms[formName].file.files[0]);
      (b) 直接追加,formData.append("file", myFile, "myFile.txt");  //myFile:待上传的文件对象
(3)把JSON数据转化为字符串(使用stringify方法),然后根据此字符串创建一个Blob,该Blob使得 
   multipart请求中关于表单数据部分的Content-type为application/json,而不是file类型;
(4)发送请求。

formData = new FormData();

formData.append("file", document.forms[formName].file.files[0]);
formData.append('properties', new Blob([JSON.stringify({
                "name": "root",
                "password": "root"                    
            })], {
                type: "application/json"
            }));
Request Payload:

Accept:application/json, text/plain, */*
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryEBoJzS3HQ4PgE1QB

------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="file"; filename="myfile.txt"
Content-Type: application/txt


------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="properties"; filename="blob"
Content-Type: application/json


------WebKitFormBoundaryvijcWI2ZrZQ8xEBN--

参考链接:https://stackoverflow.com/questions/21329426/spring-mvc-multipart-request-with-json

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值