// HTML 部分
<form id="uploadForm">
<input type="file" id="fileInput" name="file" />
<button type="submit">上传</button>
</form>
<div id="progress"></div>
// JavaScript 部分
document.getElementById('uploadForm').addEventListener('submit', function(event) {
event.preventDefault(); // 阻止表单默认提交行为
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
if (!file) {
alert('请选择一个文件');
return;
}
const formData = new FormData();
formData.append('file', file);
const xhr = new XMLHttpRequest();
xhr.open('POST', '/upload', true);
// 设置进度条
xhr.upload.onprogress = function(event) {
if (event.lengthComputable) {
const percentComplete = (event.loaded / event.total) * 100;
document.getElementById('progress').innerText = `上传进度: ${percentComplete.toFixed(2)}%`;
}
};
xhr.onload = function() {
if (xhr.status === 200) {
alert('文件上传成功');
} else {
alert('文件上传失败');
}
};
xhr.onerror = function() {
alert('上传过程中发生错误');
};
xhr.send(formData);
});
div。FormData 对象将文件数据封装为可以发送的形式。XMLHttpRequest 发送 POST 请求到服务器端的 /upload 路径。xhr.upload.onprogress 事件监听上传进度,并更新页面上的进度信息。上一篇:js 读取本地文件
下一篇:js 大文件上传
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站