Search code examples
webfile-uploadserverclientprotocols

Mirror files from local machine to website automatically


For an exhibition setting, I have an installation, where users can continuously create and save images. These images come all to the same folder. I want this folder to be mirrored to my websites server, so I can use these images and display them, ready to be downloaded by the creators/the user.

I have no idea, where to start, and Google hasnt been really helpful, because I couldnt distinguish what I want from the common question "how to setup an upload form", which wont help in my case, I guess.

It would be super helpful, if someone could point me to the right directions, what scripts or tools I need to setup.

And to be clear: my concern is only the transfer between client and server. All other parts I have already managed


Solution

  • This is how I would do it with a simple typescript application.It watches a folder, and when a file is created (that meets requirements - in this example, it must be an image) is makes a POST request with that image to a server endpoint. (And when the server receives the file you can do something similar, except instead of sending the file to a server, you can move it to your website's images folder).

    For my answer you have to download the packages fs-extra (fs functions not included in fs), chokidar (file-folder watcher), axios (http requests wrapper) using npm/pnpm/yarn.

    import * as fs from 'fs-extra';
    import * as chokidar from 'chokidar';
    import axios from 'axios';
    
    async function uploadImageToServer(imagePath: string): Promise<void> {
        const image = await fs.readFile(imagePath);
        // Modify the URL to match your server endpoint
        const serverURL = 'http://example.com/upload';
        try {
            await axios.post(serverURL, image, {
                headers: {
                    'Content-Type': 'image/jpeg', // Modify this if your images have a different format
                },
            });
            console.log(`Image uploaded: ${imagePath}`);
        } catch (error) {
            console.error(`Error uploading image: ${error}`);
        }
    }
    
    function startWatchingFolder(folderPath: string): void {
        chokidar.watch(folderPath).on('add', (filePath) => {
            // Modify the condition based on the image file types you want to process
            if (filePath.endsWith('.jpg') || filePath.endsWith('.png')) {
                uploadImageToServer(filePath);
            }
        });
    }
    
    // Start watching the folder
    const folderPath = '.'; // Replace with the actual folder path
    startWatchingFolder(folderPath);