1、传递单文件
首先html文件中有个<input type=”file” name=”file” id=”file”/>元素。
前台js写法:
var formData=new FormData();formData.append("file",$("#file")[0].files[0]);formData.append("type",type);//也可以传递其他字段$.ajax({ type:"post", url:" testController/uploadFile", data:formData, contentType: false, processData: false, dataType:"json", success:function(res){ }, error:function (msg) { }})
后台接收方法:
@RestController@RequestMapping("testController")public class testController { @RequestMapping("/uploadFile") public String uploadFile (MultipartFile file,String type) { //操作 }}
2、传递多文件
html文件中需要有个form表单:
前台js写法:
var formData=new FormData($("#form")[0]); formData.append("type",type);//也可以添加其他字段$.ajax({ type:"post", url:" testController/uploadFiles", data:formData, contentType: false, processData: false, dataType:"json", success:function(res){ }, error:function (msg) { }})
后台接收方法:
@RestController@RequestMapping("testController")public class testController { @RequestMapping("/uploadFiles") public String uploadFile (MultipartFile[] files,String type) { //操作 }}