‘).addClass(‘loading-indicator loading’)
.html(`
${message}`);
$(‘.container’).append($loading);
}
// 工具函数:隐藏加载状态
function hideLoading() {
$(‘.loading-indicator’).remove();
}
// 浏览器兼容性检查
function checkCompatibility() {
const issues = [];
// 检查File API支持
if (!window.File || !window.FileList || !window.FileReader) {
issues.push(‘当前浏览器不支持File API’);
}
// 检查ArrayBuffer支持
if (!window.ArrayBuffer) {
issues.push(‘当前浏览器不支持ArrayBuffer’);
}
// 检查Uint8Array支持
if (!window.Uint8Array) {
issues.push(‘当前浏览器不支持Uint8Array’);
}
// 检查jQuery
if (typeof $ === ‘undefined’) {
issues.push(‘jQuery未加载’);
}
// 检查MDB解析库
if (typeof MDBParser === ‘undefined’) {
issues.push(‘MDB解析库未加载’);
}
if (issues.length > 0) {
showError(‘兼容性问题:’ + issues.join(‘;’));
return false;
}
return true;
}
// 页面加载时执行兼容性检查
setTimeout(checkCompatibility, 500);
});
3. 兼容性问题解决方案
问题1:浏览器不支持File API
解决方案:
// 检查File API支持
function checkFileAPI() {
if (!window.File || !window.FileList || !window.FileReader) {
// 降级方案:使用Flash或ActiveX(不推荐,仅用于极端情况)
// 或者提示用户升级浏览器
alert(‘您的浏览器版本过低,请使用Chrome 13+、Firefox 3.6+、Safari 6+或Edge’);
return false;
}
return true;
}
// 在文件选择前检查
$(‘#mdbFile’).on(‘click’, function(e) {
if (!checkFileAPI()) {
e.preventDefault();
return false;
}
});
问题2:IE浏览器兼容性(IE < 10)
解决方案:
// IE兼容性处理
function getIEVersion() {
const ua = window.navigator.userAgent;
const msie = ua.indexOf('MSIE ');
if (msie > 0) {
// IE 10 or older
return parseInt(ua.substring(msie + 5, ua.indexOf(‘.’, msie)), 10);
}
const trident = ua.indexOf(‘Trident/’);
if (trident > 0) {
// IE 11
return 11;
}
return 0; // not IE
}
// 针对IE的特殊处理
function handleIECompatibility() {
const ieVersion = getIEVersion();
if (ieVersion > 0 && ieVersion < 10) {
// IE 9及以下使用ActiveX
return {
useActiveX: true,
message: 'IE9及以下版本需要使用ActiveX,请在Internet选项中启用ActiveX控件'
};
}
return { useActiveX: false };
}
// 修改文件读取逻辑
function readFileWithCompatibility(file) {
const ieInfo = handleIECompatibility();
if (ieInfo.useActiveX) {
// IE 9及以下的ActiveX方案
return readWithActiveX(file);
} else {
// 标准方案
return readWithFileAPI(file);
}
}
问题3:大文件内存溢出
解决方案:
// 分块读取大文件
function readLargeFile(file, chunkSize = 1024 * 1024) {
return new Promise((resolve, reject) => {
const chunks = [];
let offset = 0;
const reader = new FileReader();
reader.onerror = reject;
reader.onload = function(e) {
chunks.push(e.target.result);
offset += chunkSize;
if (offset < file.size) {
readNextChunk();
} else {
// 合并所有chunks
const totalSize = chunks.reduce((acc, chunk) => acc + chunk.byteLength, 0);
const result = new Uint8Array(totalSize);
let pos = 0;
chunks.forEach(chunk => {
result.set(new Uint8Array(chunk), pos);
pos += chunk.byteLength;
});
resolve(result);
}
};
function readNextChunk() {
const slice = file.slice(offset, offset + chunkSize);
reader.readAsArrayBuffer(slice);
}
readNextChunk();
});
}
// 使用示例
$(‘#mdbFile’).on(‘change’, async function(e) {
const file = e.target.files[0];
if (file.size > 50 * 1024 * 1024) {
// 大于50MB使用分块读取
showLoading(‘大文件模式:分块读取中…’);
try {
const buffer = await readLargeFile(file);
parseMDBFile(buffer);
} catch (error) {
showError(‘大文件读取失败:’ + error.message);
}
} else {
// 小文件直接读取
const reader = new FileReader();
reader.onload = (e) => parseMDBFile(new Uint8Array(e.target.result));
reader.readAsArrayBuffer(file);
}
});
问题4:跨浏览器事件处理
解决方案:
// 统一事件处理
function addEvent(element, event, handler) {
if (element.addEventListener) {
element.addEventListener(event, handler, false);
} else if (element.attachEvent) {
element.attachEvent(‘on’ + event, handler);
} else {
element[‘on’ + event] = handler;
}
}
// 文件拖放支持
function setupDragAndDrop() {
const dropZone = document.body;
addEvent(dropZone, ‘dragover’, function(e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = ‘copy’;
this.style.background = ‘#e9ecef’;
});
addEvent(dropZone, ‘dragleave’, function(e) {
e.stopPropagation();
e.preventDefault();
this.style.background = ”;
});
addEvent(dropZone, ‘drop’, function(e) {
e.stopPropagation();
e.preventDefault();
this.style.background = ”;
const files = e.dataTransfer.files;
if (files.length > 0) {
const file = files[0];
// 触发文件选择事件
$(‘#mdbFile’)[0].files = files;
$(‘#mdbFile’).trigger(‘change’);
}
});
}
// 初始化拖放
setupDragAndDrop();
方案二:服务器端代理方案(推荐用于生产环境)
由于纯前端方案存在性能和兼容性限制,推荐使用服务器端代理方案。
1. Node.js Express服务器
// server.js
const express = require(‘express’);
const multer = require(‘multer’);
const { Pool } = require(‘pg’);
const fs = require(‘fs’);
const path = require(‘path’);
const csv = require(‘csv-stringify’);
const app = express();
const upload = multer({ dest: ‘uploads/’ });
// 数据库连接配置(用于转换后的数据存储)
const pool = new Pool({
user: ‘your_user’,
host: ‘localhost’,
database: ‘your_db’,
password: ‘your_password’,
port: 5432,
});
// 允许CORS
app.use((req, res, next) => {
res.header(‘Access-Control-Allow-Origin’, ‘*’);
res.header(‘Access-Control-Allow-Headers’, ‘Origin, X-Requested-With, Content-Type, Accept’);
next();
});
app.use(express.json());
// 上传并解析MDB文件
app.post(‘/api/parse-mdb’, upload.single(‘mdbFile’), async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ error: ‘没有上传文件’ });
}
const filePath = req.file.path;
const originalName = req.file.originalname;
// 使用mdb-tools命令行工具解析
const { exec } = require(‘child_process’);
const util = require(‘util’);
const execPromise = util.promisify(exec);
// 获取所有表名
const { stdout: tablesOutput } = await execPromise(`mdb-tables -1 “${filePath}”`);
const tableNames = tablesOutput.trim().split(‘\n’).filter(t => t);
const result = {
fileName: originalName,
tables: {}
};
// 逐个表导出为CSV
for (const tableName of tableNames) {
const csvPath = `${filePath}_${tableName}.csv`;
await execPromise(`mdb-export “${filePath}” “${tableName}” > “${csvPath}”`);
// 读取CSV内容
const csvContent = fs.readFileSync(csvPath, ‘utf8’);
// 解析CSV为JSON
const rows = [];
const lines = csvContent.split(‘\n’);
const headers = lines[0].split(‘,’).map(h => h.trim().replace(/”/g, ”));
for (let i = 1; i < lines.length; i++) {
if (lines[i].trim()) {
const values = parseCSVLine(lines[i]);
const row = {};
headers.forEach((header, index) => {
row[header] = values[index] || ”;
});
rows.push(row);
}
}
result.tables[tableName] = {
columns: headers.map(h => ({ name: h })),
rows: rows,
rowCount: rows.length
};
// 清理临时文件
fs.unlinkSync(csvPath);
}
// 清理上传的MDB文件
fs.unlinkSync(filePath);
res.json(result);
} catch (error) {
console.error(‘解析错误:’, error);
res.status(500).json({ error: ‘解析失败: ‘ + error.message });
}
});
// 获取表数据(分页)
app.get(‘/api/table-data’, async (req, res) => {
try {
const { tableName, page = 1, limit = 100 } = req.query;
const offset = (page – 1) * limit;
// 这里假设数据已存储在PostgreSQL中
const query = `SELECT * FROM ${tableName} LIMIT $1 OFFSET $2`;
const result = await pool.query(query, [limit, offset]);
const countQuery = `SELECT COUNT(*) FROM ${tableName}`;
const countResult = await pool.query(countQuery);
res.json({
tableName,
rows: result.rows,
total: parseInt(countResult.rows[0].count),
page: parseInt(page),
pages: Math.ceil(countResult.rows[0].count / limit)
});
} catch (error) {
console.error(‘查询错误:’, error);
res.status(500).json({ error: ‘查询失败: ‘ + error.message });
}
});
// 导出CSV
app.get(‘/api/export-csv’, async (req, res) => {
try {
const { tableName } = req.query;
if (!tableName) {
return res.status(400).json({ error: ‘缺少表名参数’ });
}
// 查询所有数据
const result = await pool.query(`SELECT * FROM ${tableName}`);
// 转换为CSV
csv.stringify(result.rows, { header: true }, (err, output) => {
if (err) {
return res.status(500).json({ error: ‘CSV生成失败’ });
}
res.setHeader(‘Content-Type’, ‘text/csv’);
res.setHeader(‘Content-Disposition’, `attachment; filename=”${tableName}.csv”`);
res.send(output);
});
} catch (error) {
console.error(‘导出错误:’, error);
res.status(500).json({ error: ‘导出失败: ‘ + error.message });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`服务器运行在 http://localhost:${PORT}`);
});
// 辅助函数:解析CSV行(处理引号和逗号)
function parseCSVLine(line) {
const result = [];
let current = ”;
let inQuotes = false;
for (let i = 0; i < line.length; i++) {
const char = line[i];
if (char === '"') {
if (inQuotes && line[i + 1] === '"') {
current += '"';
i++;
} else {
inQuotes = !inQuotes;
}
} else if (char === ',' && !inQuotes) {
result.push(current.trim().replace(/^"|"$/g, ''));
current = '';
} else {
current += char;
}
}
result.push(current.trim().replace(/^"|"$/g, ''));
return result;
}
2. 客户端调用服务器API
// 前端调用服务器API
$(document).ready(function() {
const API_BASE = 'http://localhost:3000/api';
// 文件上传并解析
$('#mdbFile').on('change', async function(e) {
const file = e.target.files[0];
if (!file) return;
const formData = new FormData();
formData.append('mdbFile', file);
showLoading('正在上传并解析MDB文件...');
try {
const response = await fetch(`${API_BASE}/parse-mdb`, {
method: 'POST',
body: formData
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
if (result.error) {
showError(result.error);
return;
}
// 存储结果
window.mdbData = result;
// 填充表选择器
const $select = $('#tableSelect');
$select.empty();
$select.append('‘);
Object.keys(result.tables).forEach(tableName => {
$select.append(``);
});
$(‘.table-selector’).show();
hideLoading();
} catch (error) {
showError(‘请求失败:’ + error.message);
console.error(‘API错误:’, error);
}
});
// 加载表数据(分页)
$(‘#loadTable’).on(‘click’, async function() {
const tableName = $(‘#tableSelect’).val();
if (!tableName) {
showError(‘请先选择一个数据表!’);
return;
}
showLoading(‘正在加载表数据…’);
try {
const response = await fetch(
`${API_BASE}/table-data?tableName=${encodeURIComponent(tableName)}&page=1&limit=100`
);
const result = await response.json();
if (result.error) {
showError(result.error);
return;
}
// 显示数据
displayServerData(result);
$(‘.data-section’).show();
hideLoading();
} catch (error) {
showError(‘加载失败:’ + error.message);
}
});
// 导出CSV
$(‘#exportCSV’).on(‘click’, async function() {
const tableName = $(‘#tableSelect’).val();
if (!tableName) {
showError(‘请先选择一个数据表!’);
return;
}
showLoading(‘正在导出CSV…’);
try {
const response = await fetch(
`${API_BASE}/export-csv?tableName=${encodeURIComponent(tableName)}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// 创建下载链接
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement(‘a’);
a.href = url;
a.download = `${tableName}.csv`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
hideLoading();
} catch (error) {
showError(‘导出失败:’ + error.message);
}
});
// 显示服务器返回的数据
function displayServerData(data) {
const $preview = $(‘#dataPreview’);
$preview.empty();
const $table = $(‘
‘).addClass(‘data-table’);
const $thead = $(‘
‘);
const $tbody = $(‘
‘);
// 表头
if (data.rows.length > 0) {
const $headerRow = $(‘
‘);
Object.keys(data.rows[0]).forEach(key => {
$headerRow.append(`
${escapeHtml(key)} |
`);
});
$thead.append($headerRow);
// 数据行
data.rows.forEach(row => {
const $row = $(‘
‘);
Object.keys(row).forEach(key => {
$row.append(`
${escapeHtml(String(row[key]))} |
`);
});
$tbody.append($row);
});
}
$table.append($thead).append($tbody);
$preview.append($table);
// 分页信息
const $pagination = $(‘
‘).addClass(‘pagination-info’)
.html(`
表名:${data.tableName}
当前页:${data.page} / ${data.pages}
总记录数:${data.total}
`);
$preview.append($pagination);
// 分页事件
$(‘#prevPage’).on(‘click’, () => loadPage(data.tableName, data.page – 1));
$(‘#nextPage’).on(‘click’, () => loadPage(data.tableName, data.page + 1));
}
// 加载指定页码
async function loadPage(tableName, page) {
if (page < 1) return;
showLoading(`正在加载第${page}页...`);
try {
const response = await fetch(
`${API_BASE}/table-data?tableName=${encodeURIComponent(tableName)}&page=${page}&limit=100`
);
const result = await response.json();
if (result.error) {
showError(result.error);
return;
}
displayServerData(result);
hideLoading();
} catch (error) {
showError('加载失败:' + error.message);
}
}
});
3. 安装依赖
# 初始化项目
npm init -y
# 安装依赖
npm install express multer csv-stringify
# 安装mdb-tools(Linux/Mac)
# Ubuntu/Debian: sudo apt-get install mdbtools
# Mac: brew install mdbtools
# Windows: 需要下载mdbtools for Windows或使用WSL
常见兼容性问题及解决方案总结
1. 浏览器支持矩阵
浏览器
File API
ArrayBuffer
Uint8Array
推荐方案
Chrome 13+
✅
✅
✅
纯前端
Firefox 3.6+
✅
✅
✅
纯前端
Safari 6+
✅
✅
✅
纯前端
Edge 12+
✅
✅
✅
纯前端
IE 10
✅
✅
✅
纯前端
IE 9
⚠️
✅
✅
服务器端
IE 8
❌
❌
❌
服务器端
2. 性能优化建议
// 1. 使用Web Worker处理大文件
// worker.js
self.addEventListener('message', function(e) {
const buffer = e.data;
// 在Worker中解析MDB
const result = parseMDBInWorker(buffer);
self.postMessage(result);
});
// 主线程
const worker = new Worker('worker.js');
worker.postMessage(buffer);
worker.onmessage = function(e) {
const result = e.data;
// 处理结果
};
// 2. 使用IndexedDB缓存数据
function cacheToIndexedDB(tableName, data) {
return new Promise((resolve, reject) => {
const request = indexedDB.open(‘MDBCache’, 1);
request.onupgradeneeded = function(e) {
const db = e.target.result;
if (!db.objectStoreNames.contains(tableName)) {
db.createObjectStore(tableName, { keyPath: ‘id’, autoIncrement: true });
}
};
request.onsuccess = function(e) {
const db = e.target.result;
const transaction = db.transaction([tableName], ‘readwrite’);
const store = transaction.objectStore(tableName);
// 清空旧数据
store.clear();
// 添加新数据
data.forEach(item => store.add(item));
transaction.oncomplete = () => resolve();
transaction.onerror = () => reject();
};
});
}
// 3. 内存管理
function cleanupMemory() {
// 清理全局变量
window.mdbData = null;
window.currentTable = null;
// 强制垃圾回收(如果可用)
if (window.gc) {
window.gc();
}
}
3. 安全考虑
// 1. 文件类型验证
function validateFile(file) {
const allowedTypes = [
‘application/x-msaccess’, // MDB MIME类型
‘application/octet-stream’ // 备用类型
];
const extension = file.name.split(‘.’).pop().toLowerCase();
if (extension !== ‘mdb’) {
throw new Error(‘只支持MDB文件格式’);
}
// 可选:检查文件魔数(Magic Number)
// MDB文件通常以0x00010000开头
return true;
}
// 2. XSS防护
function sanitizeInput(input) {
const div = document.createElement(‘div’);
div.textContent = input;
return div.innerHTML;
}
// 3. 文件大小限制
const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB
$(‘#mdbFile’).on(‘change’, function(e) {
const file = e.target.files[0];
if (file.size > MAX_FILE_SIZE) {
showError(`文件大小超过限制(最大${MAX_FILE_SIZE / 1024 / 1024}MB)`);
$(this).val(”);
return;
}
});
总结
本文详细介绍了使用JavaScript和jQuery读取MDB文件的两种主要方案:
纯前端方案
:适用于小文件、快速原型开发,但存在兼容性和性能限制
服务器端代理方案
:适用于生产环境,性能更好,兼容性更广
关键要点:
浏览器无法直接解析MDB文件,需要依赖专门的库或服务器端转换
必须处理各种浏览器兼容性问题,特别是IE浏览器
大文件需要分块读取或使用服务器端方案
安全性和性能优化是生产环境必须考虑的因素
根据实际需求选择合适的方案,并充分测试在目标浏览器中的表现,才能确保MDB文件读取功能的稳定性和可用性。