async function uploadFile(file) { const formData = new FormData(); formData.append('video', file); try { const response = await fetch('YOUR_UPLOAD_URL', { method: 'POST', body: formData, }); if (!response.ok) { throw new Error(`Upload failed: ${response.statusText}`); } const result = await response.json(); console.log('Upload successful:', result); } catch (error) { console.error('Error uploading file:', error); } } async function uploadFiles(files, concurrencyLimit) { const uploadQueue = []; const results = []; for (const file of files) { const uploadPromise = uploadFile(file).then(result => { results.push(result); }); uploadQueue.push(uploadPromise); // 控制并发数 if (uploadQueue.length >= concurrencyLimit) { await Promise.race(uploadQueue); // 等待最先完成的上传 uploadQueue.splice(uploadQueue.findIndex(p => p === uploadPromise), 1); // 移除已完成的上传 } } // 等待所有剩余的上传完成 await Promise.all(uploadQueue); return results; } // 使用示例 const fileInput = document.getElementById('fileInput'); const uploadButton = document.getElementById('uploadButton'); uploadButton.addEventListener('click', () => { const files = Array.from(fileInput.files); const concurrencyLimit = 3; // 设置并发数 uploadFiles(files, concurrencyLimit) .then(results => { console.log('All uploads completed:', results); }) .catch(error => { console.error('Error during uploads:', error); }); });
标签:files,const,results,uploadQueue,并发,file,error,JS,上传 From: https://www.cnblogs.com/llcdbk/p/18380569