用户点击按钮或其他标签的click事件,来触发下面的事件,先创建一个type为file输入框在document下,加入change事件回调,最后再调用这个输入框的click事件。
const fileInput = document.createElement(\'input\');
fileInput.setAttribute(\'type\', \'file\');
fileInput.setAttribute(\'accept\', \'*\');
fileInput.addEventListener(\'change\', () => {
const file = fileInput.files[0];
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
if (file.size / 1024 / 1024 > 80) {
console.log(\'文件大小不超过80Mb\');
return;
}
const data = new FormData();
data.append(\'file\', file);
let r = new XMLHttpRequest();
r.open("post", address + `file`);
r.onloadend = () => {
console.log(JSON.parse(r.responseText))
}
r.send(data);
};
});
fileInput.click();