这里使用了springboot项目
html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/jquery-3.3.1.js" ></script>
</head>
<body>
<h1>你好,世界!</h1>
<form id="from1" enctype="multipart/form-data">
<input type="file" name="file" id="upfile" multiple="multiple" value="选择文件">
<input type="button" value="提交" id="btn"/>
</form>
</body>
<script >
$("#btn").click(function(){
var formData = new FormData($("#from1")[0]);/*传多个文件 $("#from1")[0]*/
//var formData = new FormData();
//formData.append("file",$("#upfile")[0].files[0]); /*传单个文件 */
$.ajax({
url: "/upload",
type: "POST",
data: formData,
/**
*必须false才会自动加上正确的Content-Type
*/
contentType: false,
/**
* 必须false才会避开jQuery对 formdata 的默认处理
* XMLHttpRequest会对 formdata 进行正确的处理
*/
processData: false,
success: function (data) {
alert("上传成功!"+data);
//console.log(data);
},
error: function () {
alert("上传失败!");
}
});
});
</script>
</html>
后台controller
package com.example.demo.action;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import java.util.HashMap;
import java.util.Map;
@Controller
public class IndexAction {
@RequestMapping("/index")
public String index(ModelAndView model){
//model.setViewName("index");
return "index";
}
//返回json格式的数据
@RequestMapping("/upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile[] files){
MultipartFile file=null;
for(int i=0;i<files.length;i++){
file=files[i];
System.out.println(file.getOriginalFilename());
}
Map map = new HashMap<>();
map.put("return","success");
String json = JSON.toJSONString(map);
return json;
}
}