- html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传文件示例</title>
</head>
<body>
<input id="file" type="file" multiple/>
</body>
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js"></script>
<script>
$("#file").change(function () {
var files=this.files;
var formData = new FormData();
for(var i=0;i<files.length;i++){
formData.append('files',files[i]);
}
$.ajax({
url:"/file",
type: "POST",
data: formData,
contentType: false,
processData: false,
success:function(res){
console.log("上传成功")
},
error:function(err){
}
})
})
</script>
</html>
- SpringBoot后端代码
@PostMapping("file")
@ResponseBody
public Object file(MultipartFile[] files) throws IOException {
for (MultipartFile file: files){
Path uploadPath = Paths.get("C:/123456");
if (!Files.exists(uploadPath))Files.createDirectories(uploadPath);
Path sourcePath = uploadPath.resolve(file.getOriginalFilename());
InputStream is = file.getInputStream();
Files.copy(is, sourcePath, StandardCopyOption.REPLACE_EXISTING);
is.close();
}
return 200;
}
- 复制以上代码直接测试!