XMLHttpRequest 实现文件上传
//XHR 文件上传可以查看进度
const uploadBtn = document.querySelector(".upload")
uploadBtn.onclick = function(){
//1.创建对象
const xhr = new XMLHttpRequest()
//2.监听结果
xhr.onload = function(){
console.log(xhr.response)
}
// 文件上传进度
xhr.onprogress = function(event){
console.log(event)
}
xhr.responseType ="json"
xhr.open("post","http://123.207.32.32:1888/02_param/upload")
//表单
const imgEl = document.querySelector("input")
// 获取文件
const file = imgEl.files[0]
const formData = new FormData()
formData.append("avatar",file)
xhr.send(formData)
}
Fetch文件上传
const uploadBtn = document.querySelector(".upload")
uploadBtn.onclick = async function(){
const imgEl = document.querySelector("input")
// 获取文件
const file = imgEl.files[0]
const formData = new FormData()
formData.append("avatar",file)
const response = await fetch("http://123.207.32.32:1888/02_param/upload",{
method:"post",
body:formData
})
const res = await response.json()
console.log("res",res)
}