以下是一个示例代码,用于在上传文件超过50MB时显示提示信息:
// HTML 部分
// JavaScript 部分
document.getElementById('uploadForm').addEventListener('submit', function(e) {
e.preventDefault(); // 阻止表单提交
var fileInput = document.getElementById('fileInput');
var file = fileInput.files[0];
if (file.size > 50 * 1024 * 1024) {
alert('哦,不!上传文件不能超过50MB!');
return;
}
var formData = new FormData();
formData.append('file', file);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// 上传成功的处理逻辑
console.log('上传成功!');
}
};
xhr.send(formData);
});
在上述代码中,我们首先获取文件的大小,如果超过50MB,则显示提示信息并返回。否则,我们使用FormData
对象来构建表单数据,并使用XMLHttpRequest
对象发送POST
请求。在onreadystatechange
回调函数中,我们可以处理上传成功的逻辑。