关于指定文件(input type=file)POST表单及浏览器自动重复上传并确认刷新时间的技术咨询
Great questions! Let's break them down one by one to give you clear, actionable solutions:
<input type="file">? Browser security policies prevent websites from directly specifying or auto-selecting local files (this protects users from malicious sites accessing their data without consent). However, once a user manually selects a file through the <input type="file"> element, you can capture the corresponding File object via the File API and reuse it for uploads later—no need for the user to reselect the file each time.
Here's a quick snippet to capture and store a selected file:
<input type="file" id="fileInput"> <button onclick="storeFile()">Save File for Later Use</button> <script> let selectedFile; function storeFile() { const fileInput = document.getElementById('fileInput'); if (fileInput.files.length > 0) { selectedFile = fileInput.files[0]; console.log(`Saved file reference: ${selectedFile.name}`); } else { alert('Please select a file first!'); } } </script>
Let's split this into two manageable parts:
Part A: Auto-repeat uploads with confirmation on refresh
To make auto-uploads persist across page refreshes, we need to store the selected file (since in-memory variables get cleared when the page reloads). localStorage can't store File objects directly, so we'll use IndexedDB to save the file blob. We'll also add a prompt to confirm if the user wants to continue auto-uploads after a refresh, and warn them before they leave/refreshes while uploads are running.
Here's a complete working example:
<input type="file" id="fileInput"> <button onclick="startAutoUpload()">Start Auto Upload</button> <button onclick="stopAutoUpload()">Stop Auto Upload</button> <script> let uploadInterval; let db; // Initialize IndexedDB to store our file async function initFileStore() { return new Promise((resolve, reject) => { const request = indexedDB.open('PersistentFileStore', 1); request.onupgradeneeded = (e) => { db = e.target.result; db.createObjectStore('uploadFiles', { keyPath: 'id' }); }; request.onsuccess = (e) => { db = e.target.result; resolve(); }; request.onerror = (e) => reject(e.target.error); }); } // Save selected file to IndexedDB async function saveSelectedFile(file) { await initFileStore(); const transaction = db.transaction('uploadFiles', 'readwrite'); const store = transaction.objectStore('uploadFiles'); store.put({ id: 'activeUpload', blob: file }); await transaction.complete; } // Retrieve stored file from IndexedDB async function getStoredFile() { await initFileStore(); const transaction = db.transaction('uploadFiles', 'readonly'); const store = transaction.objectStore('uploadFiles'); return new Promise((resolve) => { const request = store.get('activeUpload'); request.onsuccess = () => resolve(request.result?.blob); }); } // Core upload function async function uploadStoredFile() { const file = await getStoredFile(); if (!file) return; const formData = new FormData(); formData.append('uploadedFile', file); try { const response = await fetch('/your-upload-endpoint', { method: 'POST', body: formData }); console.log(`Uploaded ${file.name} | Status: ${response.status}`); } catch (err) { console.error(`Upload failed for ${file.name}:`, err); } } // Start auto-upload workflow async function startAutoUpload() { const fileInput = document.getElementById('fileInput'); if (!fileInput.files.length) { alert('Please select a file first!'); return; } await saveSelectedFile(fileInput.files[0]); uploadInterval = setInterval(uploadStoredFile, 5000); // Upload every 5 seconds console.log('Auto-upload started'); // Warn user before leaving/refreshing window.onbeforeunload = () => { return 'Auto-upload is running. Are you sure you want to refresh or leave?'; }; } // Stop auto-uploads function stopAutoUpload() { clearInterval(uploadInterval); window.onbeforeunload = null; console.log('Auto-upload stopped'); } // On page load, check for stored file and ask to resume window.addEventListener('load', async () => { const storedFile = await getStoredFile(); if (storedFile) { const resume = confirm('A file was set for auto-upload. Do you want to resume?'); if (resume) { uploadInterval = setInterval(uploadStoredFile, 5000); window.onbeforeunload = () => { return 'Auto-upload is running. Are you sure you want to refresh or leave?'; }; console.log('Auto-upload resumed'); } } }); </script>
Part B: POST a form with a specified file
Once you have a File object (either from user selection or retrieved from storage), you can create a FormData object, attach the file (and any other form fields), then send a POST request using fetch (modern browsers) or XMLHttpRequest (for older support).
Example with fetch (recommended):
async function submitFileForm(file) { const formData = new FormData(); // Append the file (match the field name your backend expects) formData.append('userFile', file); // Add additional form fields if needed formData.append('uploadNote', 'Auto-repeated upload job'); try { const response = await fetch('/your-form-submit-endpoint', { method: 'POST', body: formData // No need to set Content-Type—browser handles this automatically with a boundary }); if (response.ok) { console.log('File uploaded successfully!'); const result = await response.json(); // Parse backend JSON response console.log('Backend response:', result); } else { console.error('Upload failed with status:', response.status); } } catch (error) { console.error('Network error during upload:', error); } } // Usage: Call this after getting a File object // submitFileForm(selectedFile);
Example with XMLHttpRequest (for legacy browsers):
function submitFileViaXHR(file) { const formData = new FormData(); formData.append('userFile', file); formData.append('uploadNote', 'Auto-repeated upload job'); const xhr = new XMLHttpRequest(); xhr.open('POST', '/your-form-submit-endpoint'); xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 300) { console.log('Upload successful!'); const result = JSON.parse(xhr.responseText); console.log('Backend response:', result); } else { console.error('Upload failed:', xhr.statusText); } }; xhr.onerror = function() { console.error('Network error occurred during upload'); }; xhr.send(formData); }
内容的提问来源于stack exchange,提问作者Jeronimo Vilar

