文件对象
# 文件对象
<!-- 默认是单文件上传 赋予 multile属性可以多文件上传 -->
<input type='file' id='file' multile>
<button onclick='sendFile()'>上传文件</button>
<img id='img' src='' widhth='200'>
1
2
3
4
2
3
4
function SsendFile() {
const file = document.querySelector('#file')
console.log(file) //获取input按钮
console.log(file.files) // 获得文件对象 用户上传的文件都在里面
const fileObj =file.files[0] //只有单文件则为第0个 如有多个需要遍历 files伪数组
//预览 如是图片文件,可以处理图片预览
const blob = windows.URL.createObjectURL(fileObj)
console.log(blob) //返回的图片url 直接用img 赋予src
document.querySelector('#img').src = blob
// 发送请求
// 然后把文件对象 放到 FormData 中提交给后端
const fd = new FormData()
fd.append('接口要求的名词',fileObj)
//用ajax 或者 axios 发起请求
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
编辑 (opens new window)
上次更新: 2023/12/06, 01:31:48