环境:
前端使用JQuery.ajax()
后端SpringBoot2.x
1. 前端发送
这里每次发送一个文件,多文件请参考其他博文。
1.1 重点
这里发送文件数据的时候借助了 FormData类,当然也可以不借助,自己进行封装。
在使用ajax方法的时候,需要添加配置:
contentType
默认是:application/x-www-form-urlencoded
,需要配置为multipart/form-data
,简单配置可以配置为false。
processData
默认为true
,会对传入的数据格式化为字符串,需要配置为false
。
<body>
<form id="form">
<input type="file" name="image" id="file">
<button type="button" onclick="confirmData()">提交</button>
</form>
</body>
<script>
function addDynamic() {
let formData = new FormData($('#form')[0]);
// let file = $('#file')[0].files[0];
// formData.append("file", file);
// 可以在formData中添加自己的参数
formData.append("userId", window.localStorage.getItem("userId"));
$.ajax({
url: '/tlgms/dynamic/addDynamic',
data: formData,
contentType: false,
processData: false,
type: 'post',
dataType: 'json',
success: function (res) {
// 成功参数
}
})
}
</script>
2. 后端接收
使用 MultipartFile
接受文件
@RestController
@RequestMapping("dynamic")
public class DongtaiController extends ApiController {
@PostMapping("addDynamic")
public String addDynamic(@RequestParam(required = false) MultipartFile image, Dongtai dongtai) {
String name = "src/main/webapp/static/images/upload/" + System.currentTimeMillis() + image.getOriginalFilename();
try (OutputStream outputStream = new FileOutputStream(name)){
byte[] bytes = image.getBytes();
outputStream.write(bytes);
outputStream.flush();
dongtai.setFmImg("/tlgms/" + name.substring(16));
dongtaiDao.insert(dongtai);
return JSONUtil.toJsonStr(new R(0, ""));
} catch (IOException e) {
e.printStackTrace();
return JSONUtil.toJsonStr(new R(1, ""));
}
}
}