Universal Batch File Download in Vue
When implementing batch file downloads with Vue, the naive approach of looping through URLs to create anchor tags fails because most browsers restrict concurrent downloads to around 10 files. A reliable solution involves packaging filles in to a single ZIP archive before downloading. This requires two npm packages: file-saver for saving files and jszip for archive creation.
First, install the required dependencies:
npm install file-saver jszip
Import the packages in your Vue component:
import { saveAs } from 'file-saver'
import JSZip from 'jszip'
Assuming you have file URLs from a storage service like Alibaba Cloud OSS, define an asynchronous function to fetch file contents as ArrayBuffers:
async fetchFileContent(fileUrl) {
try {
const response = await this.$axios.get(fileUrl, {
responseType: 'arraybuffer'
})
return response.data
} catch (error) {
throw new Error(`Failed to fetch ${fileUrl}: ${error}`)
}
}
Bind a click handler to your download button to orchestrate the ZIP creation and download process:
async handleBatchDownload() {
const zip = new JSZip()
const fileList = [] // Replace with your actual file data array
const fetchPromises = []
fileList.forEach((file, index) => {
// Extract clean file URL and generate unique filename to avoid deduplication
const cleanUrl = file.ossUrl.split('?')[0]
const uniqueFilename = `${file.originalName}_${index}${file.extension || ''}`
const promise = this.fetchFileContent(cleanUrl)
.then(content => {
zip.file(uniqueFilename, content, { binary: true })
})
.catch(err => {
console.error(err)
})
fetchPromises.push(promise)
})
await Promise.all(fetchPromises)
const zipBlob = await zip.generateAsync({ type: 'blob' })
saveAs(zipBlob, 'batch-download.zip')
}
If your files don’t require unique filenames (and you accept deduplication for identical names), remove the _${index} suffix from uniqueFilename.
To use this method, replace fileList with your own array of file objects containing ossUrl, originalName, and optionally extension. Ensure your Axios instance is properly configured to handle cross-origin requests from your storage provider.
This approach bypasses browser download limits by downloading all files in parallel as ArrayBuffers, packaging them into a singlee ZIP, and triggering a single download request.