Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to download images on build and serve from dist instead of remote airtable? #1663

Open
babarogic opened this issue Dec 17, 2022 · 1 comment

Comments

@babarogic
Copy link

As airtable announced new changes, any attachment URLs obtained via the Airtable Web API and the CSV export functionality will expire after a few hours.

My question is how to serve images locally from build? In other words I would like to download them on build and place them in images folder

@atflick
Copy link

atflick commented Jun 29, 2023

I use this in my plugin, first downloads to a temp directory with a .tmp file extension and then gets moved to the destination path. Can't remember why I didn't directly download to the final destination path.

const fs = require('fs')
const path = require('path')
const https = require('https')
const http = require('http')
const TMPDIR = ".cache/downloads";

  async downloadImage(url, destPath, fileName) {
    const imagePath = path.resolve(destPath, fileName);
    const encodedURI = encodeURI(url);
    const requester = url.includes('https') ? https : http;

    try {
        if (fs.existsSync(imagePath)) return;
    } catch (err) {
        console.log(err);
    }

    const tmpPath = path.resolve(TMPDIR, `${++this.tmpCount}.tmp`);
    console.log('Downloading from:', url);
    return new Promise(function(resolve, reject) {
        const file = fs.createWriteStream(tmpPath);
        requester
            .get(encodedURI, (response) => {
                response.pipe(file);
                file.on("finish", () => {
                    file.close();
                    fs.rename(tmpPath, imagePath, resolve);
                });
            })
            .on("error", (err) => {
                console.error(err.message);
                fs.unlinkSync(tmpPath); // Cleanup blank file
                reject(err);
            });
    });
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants