单个文件上传
html
<input type="file" id="file1" oninput="fileChange()" >
<img src="" alt="上传" id="upLoadImg">
js
const file1 = document.getElementById('file1')
const upLoadImg = document.getElementById('upLoadImg')
function fileChange() {
let reader = new FileReader()
reader.readAsDataURL(file1.files[0])
reader.onload = function () {
//
upLoadImg.src = reader.result
}
}
多文件上传
html
<!-- 多选文件 添加 multiple-->
<input type="file" id="file3" multiple oninput="fileAllChange()">
js
function readFileAsync(file) {
return new Promise((resolve) => {
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = function () {
resolve(this.result)
}
})
}
async function fileAllChange() {
const fileArr = Array.from(file3.files)
const resolveList = new Array()
for(let i=0;i<fileArr.length;i++){
console.log(fileArr[i])
resolveList.push(await readFileAsync(fileArr[i]))
}
// 此处 就为 上传文件的 base 64 编码 的数组
console.log(resolveList)
}