在 Web 開發中,處理用戶上傳的圖片時,前端壓縮可以有效減少服務器壓力并提升上傳效率。本文將詳細講解如何通過<input type="file">實現圖片上傳,結合 Canvas 實現圖片壓縮,并實時展示壓縮前后的圖片預覽和文件大小對比。
一、核心功能架構
我們將實現以下功能模塊:
- 文件選擇組件:使用 HTML 原生文件輸入控件
- 圖片預覽區域:展示原始圖片和壓縮后圖片
- 大小對比顯示:實時顯示壓縮前后的文件大小(KB/MB)
- 壓縮操作按鈕:觸發圖片壓縮邏輯
- 進度反饋:通過視覺提示顯示處理狀態
最終效果如下:
二、HTML 基礎結構
首先構建頁面骨架,包含文件輸入、預覽區域和信息展示模塊:
<div class="container"><h1>圖片壓縮工具</h1><!-- 文件上傳組件 --><input type="file" accept="image/*" id="imageInput" /><!-- 操作按鈕 --><button id="compressBtn" disabled>開始壓縮</button><!-- 預覽區域 --><div class="preview-container"><div class="preview-item"><h3>原始圖片</h3><div id="originalPreview"></div><span id="originalSize"></span></div><div class="preview-item"><h3>壓縮后圖片</h3><div id="compressedPreview"></div><span id="compressedSize"></span></div></div>
</div>
三、CSS 樣式設計
使用 Flex 布局實現響應式預覽,添加視覺反饋樣式:
.container {max-width: 1200px;margin: 0 auto;padding: 20px;
}.preview-container {display: flex;gap: 40px;margin-top: 30px;
}.preview-item {flex: 1;border: 1px solid #eee;padding: 20px;border-radius: 8px;
}img {max-width: 100%;max-height: 400px;object-fit: contain;display: block;margin: 20px 0;
}button {padding: 10px 20px;background-color: #4a90e2;color: white;border: none;border-radius: 4px;cursor: pointer;margin: 20px 0;
}button:disabled {background-color: #ccc;cursor: not-allowed;
}.size-info {color: #666;font-size: 0.9em;
}
四、核心 JavaScript 邏輯
1. 初始化事件綁定
const imageInput = document.getElementById('imageInput');
const compressBtn = document.getElementById('compressBtn');
const originalPreview = document.getElementById('originalPreview');
const compressedPreview = document.getElementById('compressedPreview');
const originalSize = document.getElementById('originalSize');
const compressedSize = document.getElementById('compressedSize');imageInput.addEventListener('change', handleImageChange);
compressBtn.addEventListener('click', handleCompression);
2. 圖片選擇處理函數
let selectedImage = null;function handleImageChange(e) {const file = e.target.files[0];if (file && isImageFile(file)) {selectedImage = {file: file,type: