Prevent Duplicate files uploads in CMS Datasets

,

I have an upload page where I use a repeater to manage file uploads. However, after testing, I found that it is possible to upload the same file that was previously uploaded. I want to prevent users from uploading duplicate files or files with the same name to avoid redundancy and conserve storage space in Wix. Is there a way to implement a check that validates and prevents duplicate uploads?"

I’m using Wix Editor.

i’m facing same issues

This is rudimentary but maybe a starting place.

This assumes you have a Upload File Button and a Start Upload button.

The idea is, visitor clicks the upload button and then the start upload button.

The start upload button, will trigger the code below.
Which check a CMS ( you need to creat eone for this first )
If the file name exists in the CMS then don’t upload.
If not, it will upload the file and write it’s file name to the CMS.

As I said this rudimentary and will need fleshing out for the user interaction and notifications of what’s happening.

import wixData from 'wix-data';

 

function upload() {
    $w("#uploadButton1")
        .uploadFiles()
        .then((uploadedFiles) => {
            if (uploadedFiles.length > 0) {
                const fileData = {
                    title: uploadedFiles[0].fileName,
                    url: uploadedFiles[0].fileUrl,
                };

                //== Insert into the collection after successful upload
                wixData.insert("ImageUpload", fileData)
                    .then((result) => {
                        console.log("File info saved to collection:", result);
                    })
                    .catch((err) => {
                        console.error("Error saving file info:", err);
                    });
            } else {
                console.error("No files uploaded.");
            }
        })
        .catch((uploadError) => {
            console.error("File upload error:", uploadError.errorCode, uploadError.errorDescription);
        });
}

$w("#submitButton").onClick(() => {
    const uploadedFiles = $w("#uploadButton1").value;

    if (uploadedFiles.length > 0) {
        const fileName = uploadedFiles[0].name;
//== Check if file name already exists
        wixData.query("ImageUpload")
            .eq("title", fileName)
            .find()
            .then((results) => {
                if (results.items.length > 0) {
                    console.log("ITEM Found:", results.items[0]);
                } else {
                    console.log("No Item Found. Uploading the file...");
                    upload();
                }
            })
            .catch((err) => {
                console.error("Error querying file:", err);
            });
    } else {
        console.log("No file selected. Please select a file to upload.");
    }
});

Note: I see there is some backend methods for uploads but too involved for me to investigate at this time.

1 Like