1.文件选择与本地暂存:用户选择照片后,将照片暂存到 IndexedDB。
2.检测网络状态:利用 navigator.onLine 和 window 事件监听网络状态。
3.网络恢复时批量上传:当检测到网络恢复时,读取 IndexedDB 中的照片并批量上传。
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Local Store and Upload Images Later</title>
- </head>
- <body>
- <h1>Local Store and Upload Images Later</h1>
- <input type="file" id="fileInput" multiple>
- <button id="storeButton">Store Locally</button>
-
- <script>
- const dbPromise = indexedDB.open('photosDB', 1);
- dbPromise.onupgradeneeded = event => {
- const db = event.target.result;
- if (!db.objectStoreNames.contains('photos')) {
- db.createObjectStore('photos', { keyPath: 'id', autoIncrement: true });
- }
- };
- dbPromise.onsuccess = event => {
- console.log('Database opened successfully');
- };
- dbPromise.onerror = event => {
- console.error('Database error:', event.target.errorCode);
- };
- document.getElementById('storeButton').addEventListener('click', () => {
- const fileInput = document.getElementById('fileInput');
- const files = fileInput.files;
- const db = dbPromise.result;
- const tx = db.transaction('photos', 'readwrite');
- const store = tx.objectStore('photos');
- for (let file of files) {
- const reader = new FileReader();
- reader.onload = (event) => {
- const data = event.target.result;
- store.add({ fileName: file.name, data });
- };
- reader.readAsDataURL(file);
- }
- alert('Files have been stored locally.');
- });
- function uploadPhotos() {
- const db = dbPromise.result;
- const tx = db.transaction('photos', 'readonly');
- const store = tx.objectStore('photos');
- const request = store.getAll();
- request.onsuccess = event => {
- const files = event.target.result;
- files.forEach(file => {
- const formData = new FormData();
- formData.append('file', dataURIToBlob(file.data), file.fileName);
- fetch('/upload', {
- method: 'POST',
- body: formData
- })
- .then(response => response.json())
- .then(data => {
- console.log('Success:', data);
- // 删除已上传的文件
- const delTx = db.transaction('photos', 'readwrite');
- const delStore = delTx.objectStore('photos');
- delStore.delete(file.id);
- })
- .catch(error => console.error('Error uploading file:', error));
- });
- };
- }
- function dataURIToBlob(dataURI) {
- const byteString = atob(dataURI.split(',')[1]);
- const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
- const ab = new ArrayBuffer(byteString.length);
- const ia = new Uint8Array(ab);
- for (let i = 0; i < byteString.length; i++) {
- ia[i] = byteString.charCodeAt(i);
- }
- return new Blob([ab], { type: mimeString });
- }
- window.addEventListener('online', uploadPhotos);
- </script>
- </body>
- </html>
复制代码 |