<form id="uploadForm" enctype="multipart/form-data" action="upload.php" method="POST"> <input type="file" name="file" id="uploadFile"> <input type="submit" value="上传" id="uploadBtn"> </form>
document.getElementById('uploadForm').addEventListener('submit', function (e) { e.preventDefault(); // 阻止表单的默认提交行为 var fileInput = document.getElementById('uploadFile'); var file = fileInput.files[0]; // 获取用户选择的文件 var formData = new FormData(); formData.append('file', file); // 将文件添加到表单数据中 var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { console.log('上传成功!'); } }; xhr.open('POST', 'upload.php', true); // 设置请求方式、目标URL、异步标志 xhr.upload.onprogress = function (e) { if (e.lengthComputable) { var percentComplete = (e.loaded / e.total) * 100; console.log(percentComplete + '% 已上传'); } }; xhr.send(formData); // 发送表单数据 });