批量下载多个url文件

async function downloadFile(url, filename) {
    try {
        const response = await fetch(url);
        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
        const blob = await response.blob();
        const downloadUrl = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.style.display = 'none';
        a.href = downloadUrl;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(downloadUrl);
        document.body.removeChild(a);
    } catch (err) {
        console.error(err);
    }
}


export async function batchDownload(fileUrls) {
    const downloadPromises = fileUrls.map(async (url, index) => {
        var filename = url.split("/").pop(); // 获取最后一个斜杠后的部分  
        var queryIndex = filename.indexOf("?"); // 查找问号的位置  
        if (queryIndex !== -1) {  
        filename = filename.substring(0, queryIndex); // 截取问号之前的部分作为文件名**文件名称根据实际情况命名,目前是截取部分url作为文件名**
        }  
        return downloadFile(url, filename);
    });

    try {
        await Promise.all(downloadPromises);
        console.log('All files downloaded successfully');
    } catch (err) {
        console.error('Error occurred during batch download', err);
    }
}

// 调用示例  
const urls = [  
  'https://example.com/file1.pdf',  
  'https://example.com/file2.pdf',  
  // ... 其他文件URL  
];  
batchDownload(urls);

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值