angularjs springboot上传文件ContentType:multipart/form-data

1、Http协议传输中可以传送多部分对象集合。对应的Content-Type为multipart/form-data

Content-Type: multipart/form-data; boundary=AaB03x
--AaB03x
Content-Disposition: form-data; name="field1"
Joe Blow
--AaB03x
Content-Disposition: form-data; name="pics"; filename="file1.txt"
Content-Type: text/plain
...(file1.txt的数据)...
--AaB03x--

上面为http请求时传递的实体数据,包含两个不同的对象,字符串field1与文件pics

field1=Joe Blow  pics=file1.txt

2、http使用 boundary 字符串来划分多部分对象集合指明的各类实体。在boundary 字符串指定的各个实体的起始行之前插入“--”标记(例如:--AaB03x、--THIS_STRING_SEPARATES),而在多部分对象集合对应的字符串的最后插入“--”标记(例如:--AaB03x--、--THIS_STRING_SEPARATES--)作为结束。boundary一般由浏览器自动随机生成。

使用multipart/form-data传递数据时一般不设置Content-Type,浏览器会设置该首部并带上生成的boundary,类似于

Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryzxPPZRJEmGdLBx97

主动设置Content-Type为multipart/form-data时,会丢掉boundary值,导致后台无法解析数据。

3、附angularjs与spring boot请求示例

angularjs请求:

  $http.post(url,params,{
        headers: {
            'title': 'boss',
             'userId':user.id,
             'SESSIONID': user.sessionId,
             'Content-Type': undefined
              },
             transformRequest: angular.identity
         }).success(function(data){
              if (data.success) {
                 callback(data);
              } else {
                 toastr.error('交互失败!');
                 callback(data);
             }
         }).error(function() {
               toastr.error('请求失败,请检查网络!');
         });
SpringBoot代码:
public AjaxResponseMessage addBalance(@RequestParam("file") MultipartFile file,
								@RequestParam("accountId") int accountId,
								@RequestParam("accountChange") Integer accountChange,
								@RequestParam(value = "remarks", required = false) String remarks) {

	AjaxResponseMessage ajaxResponseMessage = new AjaxResponseMessage();
	try {
		ccountService.addBalance(accountId, accountChange, remarks, file);
	 catch (Exception e) {
		ajaxResponseMessage.setSuccess(false);
	}
	return ajaxResponseMessage;
}

猜你喜欢

转载自blog.csdn.net/xinzhongyi/article/details/79975193