1. 文件下載
function downloadFile(content, filename, type) {const blob = new Blob([content], { type });const url = URL.createObjectURL(blob);const a = document.createElement('a');a.href = url;a.download = filename;a.click();URL.revokeObjectURL(url);
}// 使用示例
downloadFile('Hello, world!', 'example.txt', 'text/plain');
2. 圖片預覽
function previewImage(file) {const blob = URL.createObjectURL(file);const img = document.createElement('img');img.onload = function() {URL.revokeObjectURL(this.src); // 釋放內存};img.src = blob;document.body.appendChild(img);
}// 使用示例
const fileInput = document.querySelector('input[type="file"]');
fileInput.addEventListener('change', (e) => {previewImage(e.target.files[0]);
});
3. 大文件分片上傳
function uploadLargeFile(file, chunkSize = 1024 * 1024) {let offset = 0;const fileSize = file.size;while (offset < fileSize) {const chunk = file.slice(offset, offset + chunkSize);// 上傳chunk...offset += chunkSize;}
}