Technology Encyclopedia Home >How to implement file upload and download in PWA?

How to implement file upload and download in PWA?

Implementing file upload and download in a Progressive Web App (PWA) involves using JavaScript's File API along with Fetch API for handling HTTP requests. Here's a basic explanation and example:

File Upload

  1. HTML Setup: Create an input element of type file.

    <input type="file" id="fileInput" />
    
  2. JavaScript Handling: Use JavaScript to capture the file and send it to a server.

    document.getElementById('fileInput').addEventListener('change', function(event) {
        const file = event.target.files[0];
        const formData = new FormData();
        formData.append('file', file);
    
        fetch('/upload', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(error => console.error('Error:', error));
    });
    

File Download

  1. HTML Setup: Create a link or button to trigger the download.

    <a id="downloadLink" href="#">Download File</a>
    
  2. JavaScript Handling: Use JavaScript to fetch the file from the server and trigger the download.

    document.getElementById('downloadLink').addEventListener('click', function() {
        fetch('/download')
            .then(response => response.blob())
            .then(blob => {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = 'filename.ext'; // Specify the filename
                document.body.appendChild(a);
                a.click();
                a.remove();
                window.URL.revokeObjectURL(url);
            })
            .catch(error => console.error('Error:', error));
    });
    

Example in a PWA Context

For a PWA, you might want to store files in a cloud storage service. Tencent Cloud's Object Storage (COS) is a good choice for this purpose. Here’s how you might integrate it:

  1. Upload to COS: Use the COS SDK to upload files directly from the client.

    const COS = require('cos-js-sdk-v5');
    const cos = new COS({
        SecretId: 'YOUR_SECRET_ID',
        SecretKey: 'YOUR_SECRET_KEY'
    });
    
    cos.putObject({
        Bucket: 'examplebucket-1250000000', /* Bucket Name */
        Region: 'ap-guangzhou',           /* Region */
        Key: 'object_name',              /* Object Name */
        Body: file                         /* File to upload */
    }, function(err, data) {
        console.log(err || data);
    });
    
  2. Download from COS: Use the COS SDK to download files.

    cos.getObject({
        Bucket: 'examplebucket-1250000000', /* Bucket Name */
        Region: 'ap-guangzhou',           /* Region */
        Key: 'object_name'                  /* Object Name */
    }, function(err, data) {
        const url = window.URL.createObjectURL(new Blob([data.Body]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'filename.ext'); // Specify the filename
        document.body.appendChild(link);
        link.click();
    });
    

This approach leverages Tencent Cloud's COS for scalable and reliable file storage, making it suitable for PWAs.