<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="file">
</body>
</html>
<script>
// 获取上传文件的dom元素
let fileDom = document.querySelector('input[type="file"]')
// 创建 表单对象 formData
let formData = new FormData()
fileDom.onchange = function () {
console.log(fileDom.files[0]); //获取上传的文件
formData.append('headimgurl', fileDom.files[0])//使用append方法添加需要发送的文件(信息),第一个参数是后台指定的字段名
fetch("http://chst.vip/students/uploadStuAvatar", {
method: 'post',
//body是fetch上文件的属性
body: formData
})
.then(body => body.json())
.then(res => {
console.log(res);
})
}
</script>
formData实现文件上传
最新推荐文章于 2023-12-20 23:10:05 发布