Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Universal Batch File Download in Vue

Tech 1

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.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.