<body>
<input type="file" id="file" style="display: none;">
<button id="btn">upload</button>
</body>
<script>
let btn = document.querySelector('#btn')
let file = document.querySelector('#file')
btn.onclick = function() {
file.click() // 调取系统选择图片的弹框
}
// 监听input的file变化值
file.onchange = function (event) {
let file = event.target.files[0]
upload(file)
}
function upload(file) {
let xhr = new XMLHttpRequest()
xhr.open('post', '/upload', true)
let formData = new FormData()
formData.set('filename', file)
xhr.send(formData)
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
alert('success')
}
}
}
</script>
formdata实现图片上传
https://blog.csdn.net/weixin_41829196/article/details/88606970