最近要改造一个接口,原本是json传参,现在要加个文件,emm
RequestPart 可以帮我们做到,不同的key 以不同的content type解析
后端代码
@PostMapping("test")
@ResponseBody
public String test(@RequestPart("customer") Customer customer, @RequestPart MultipartFile file){
System.out.println(file.getOriginalFilename());
System.out.println(customer);
return "test success";
}
前端代码
$("#commit").click(function(){
var fd = new FormData();
// 第一种写法
// fd.append("customerId", 12);
// fd.append("customerName", "zhang");
// fd.append("file", $('#f')[0].files[0]);
// 第二种写法
var customer = JSON.stringify({
"customerId": 12,
"customerName": "zhang"
});
//这里包装 可以直接转换成对象
fd.append('customer', new Blob([customer], {type: "application/json"}));
fd.append("file", $('#f')[0].files[0]);
$.ajax({
url: 'http://localhost:8080/test',
type: 'post',
processData: false,
contentType: false,
data: fd,
success: function () {
alert("ok")
}
})
});
postman
默认没有这一列,需要点三个点 点出来