spring-boot上传

spring-boot的文档上说

Spring Boot embraces the Servlet 3 javax.servlet.http.Part API to support uploading files

Servlet 3解决了HttpServletRequest 对文件上传的支持问题.之前需要借助commons-upload完成的事,现在不需要依赖它了.
也就是说,在spring-boot中不能用commons-upload实现MultipartResolver接口了,下面这样定义是错误的

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

我们所要做的就是什么也不做,spring-boot默认就不用commons-upload了.下面说说具体实现

  • 文件单独上传

这个只需要用@RequestParam就可以了

upload(@RequestParam MultipartFile file)
  • 文件上传+表单上传

upload(@ModelAttribute Person person,@RequestParam MultipartFile file)
  • 上传json(解析)

upload(@RequestBody Person person)
var xhr=new XMLHttpRequest();
xhr.send(JSON.stringify(data));

前端需要设置Content-type:application/json

  • 文件上传+json(不解析)
    这个也很简单

upload(@RequestParam String person,@RequestParam MultipartFile file)
  • 文件上传+json(解析)

还想偷下懒,把json里的属性塞到Person里
刚开始想到的是

upload(@RequestBody Person person,@RequestParam MultipartFile file)

但是报415 Unsupported Media Type,看文档
上面说的用@RequestPart,然后json数据可以通过设置Content-type:application/json,让MappingJackson2HttpMessageConverter识别,把json属性塞进实体类

问题来了,怎样才能在multipart/form-data的分段里设置Content-type呢?

var form=new FormData();
var file=document.getElementById('file').files[0];
form.append("file",file );
var data={name:"TheViper",age:11};
form.append("person",new Blob([JSON.stringify(data)],{type: "application/json"}));

下载

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值