Fetch image link from wix site media the right way

Hi,
In one aspect of the code of my website, I upload an image from a short-term link onto the wix servers, only to fetch the same image again. This allows me to safely store the image over longer periods of time.
In my css collection the images keep disappearing after a couple of hours though.
Is this the right way to get the link?

It seems the issue with your images disappearing is because the short-term links you’re using aren’t being replaced with a permanent link on Wix’s servers. To ensure your images are stored safely for the long term, here’s what you can do:

  1. Upload the Image Properly: Use Wix’s APIs to upload the image directly to your Wix Media Manager or database. This will generate a permanent link for the image.
  2. Store the Permanent Link: Once the image is uploaded, save the long-term URL that Wix provides into your database or collection. This ensures the image will always be accessible.
  3. Use the Saved URL: Whenever you need to display the image, make sure you’re referencing the permanent link from your collection, not the short-term one.

This process ensures your images won’t disappear after a few hours. If you run into any issues or need more help with this, feel free to reach out!

Hi! Thanks for your response!
The uploading process works fine, I can find the images manually.
somewhere between fetching the long term link and saving it to the collection there must be an error though.
Do you know if the code looks good? Or is there a different feature that fits the purpose better?
Kind regards

If you read the Velo docs, you’ll notice that the very first line for the getDownloadUrl() function mentions that it generates a ‘temporary’ download URL for your file.

Which is probably why…

From the three lines of code that you’ve provided, it is not possible for us to debug your code since we have no idea which particular upload function are you using in your code.

But since you mentioned…

…I’m guessing you’re using the getUploadUrl() function, and in that case, as mentioned in the docs:

To get a Wix image URL that can be stored in a collection or displayed in an image element or gallery from the above object, use the following expression:

let wixImageUrl = `wix:image://v1/${response[0].file_name}/${response[0].original_file_name}#originWidth=${response[0].width}&originHeight=${response[0].height}`;

So yes, getDownloadUrl() is definitely not the function that should be used in this case.

Hope this helps! (:

Looks like you know what you’re talking about!

Would you mind helping me out one step further? Thank you so much!

// uploadImage.jsw
import wixData from ‘wix-data’;
import { mediaManager } from ‘wix-media-backend’;

// Export the function so it can be imported on the frontend
export async function saveImageToCollection(_id, imageUrl, userId) {
try {
console.log(saveImageToCollection called with _id: ${_id}, userId: ${userId}, and imageUrl: ${imageUrl});

    // Validate the imageUrl
    if (!imageUrl || typeof imageUrl !== 'string' || !isValidUrl(imageUrl)) {
        throw new Error(`Invalid imageUrl provided: ${imageUrl}`);
    }

    // Generate a timestamp (ensure it's the same for filename and collection)
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); // Replace characters not allowed in filenames

    // Generate a filename based on userId and timestamp
    const fileName = `sticker_${userId}_${timestamp}.png`;
    const destination = `/images/${fileName}`;

    console.log(`Importing image to destination: ${destination}`);

    // Import the image into Wix Media Manager
    const uploadedFile = await mediaManager.importFile(
        destination, // Specify the folder and file name
        imageUrl,
        {
            mediaOptions: {
                mimeType: 'image/png',
                mediaType: 'image'
            },
            metadataOptions: {
                isPrivate: false,
                isVisitorUpload: false
            }
        }
    );

    console.log('File successfully imported:', uploadedFile);

    // Get the download URL using mediaManager.getDownloadUrl and the fileName
    const fileDownloadUrl = await mediaManager.getDownloadUrl(uploadedFile.fileName);
    if (!fileDownloadUrl) {
        throw new Error(`Failed to retrieve file download URL for record ID ${_id} after upload.`);
    }

    console.log(`Permanent file download URL obtained: ${fileDownloadUrl}`);

    // Retrieve the existing item from the collection
    const existingItem = await wixData.get('StickerDesigns', _id);
    if (!existingItem) {
        throw new Error(`Item with _id ${_id} not found in StickerDesigns collection.`);
    }

    // Update the 'generatedImageSaved' field and add 'stickerTimestamp'
    existingItem.generatedImageSaved = fileDownloadUrl;
    existingItem.stickerTimestamp = timestamp; // Store the timestamp used in the filename

    // Save the entire item back to the collection
    const result = await wixData.update('StickerDesigns', existingItem);
    console.log(`Updated collection with permanent file download URL and stickerTimestamp for record ID: ${_id}`);

    // Return the permanent URL
    return { url: fileDownloadUrl };
} catch (error) {
    console.error(`Error in saveImageToCollection for record ID ${_id}:`, error);
    throw new Error(`Failed to save image to Wix collection for record ID ${_id}. Error: ${error.message}`);
}

}

// Helper function to validate URLs
function isValidUrl(url) {
try {
new URL(url);
return true;
} catch (error) {
return false;
}
}

Try this:

// uploadImage.jsw
import wixData from 'wix-data';
import { mediaManager } from 'wix-media-backend';

// Export the function so it can be imported on the frontend
export async function saveImageToCollection(_id, imageUrl, userId) {
    try {
        console.log('saveImageToCollection called with _id: ' + _id + ' userId: ' + userId + ' and imageUrl: ' + imageUrl);

        // Validate the imageUrl
        if (!imageUrl || typeof imageUrl !== 'string' || !isValidUrl(imageUrl)) {
            throw new Error(`Invalid imageUrl provided: ${imageUrl}`);
        }

        // Generate a timestamp (ensure it's the same for filename and collection)
        const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); // Replace characters not allowed in filenames

        // Generate a filename based on userId and timestamp
        const fileName = `sticker_${userId}_${timestamp}.png`;
        const destination = `/images/${fileName}`;

        console.log(`Importing image to destination: ${destination}`);

        // Import the image into Wix Media Manager
        const uploadedFile = await mediaManager.importFile(
            destination, // Specify the folder and file name
            imageUrl, {
                mediaOptions: {
                    mimeType: 'image/png',
                    mediaType: 'image'
                },
                metadataOptions: {
                    isPrivate: false,
                    isVisitorUpload: false
                }
            }
        );

        console.log('File successfully imported:', uploadedFile);

        const fileUrl = uploadedFile.fileUrl;

        console.log(`Permanent file URL obtained: ${fileUrl}`);

        // Retrieve the existing item from the collection
        const existingItem = await wixData.get('StickerDesigns', _id);
        if (!existingItem) {
            throw new Error(`Item with _id ${_id} not found in StickerDesigns collection.`);
        }

        // Update the 'generatedImageSaved' field and add 'stickerTimestamp'
        existingItem.generatedImageSaved = fileUrl;
        existingItem.stickerTimestamp = timestamp; // Store the timestamp used in the filename

        // Save the entire item back to the collection
        const result = await wixData.update('StickerDesigns', existingItem);
        console.log(`Updated collection with permanent file URL and stickerTimestamp for record ID: ${_id}`);

        // Return the permanent URL
        return { url: fileUrl };
    } catch (error) {
        console.error(`Error in saveImageToCollection for record ID ${_id}:`, error);
        throw new Error(`Failed to save image to Wix collection for record ID ${_id}. Error: ${error.message}`);
    }
}

// Helper function to validate URLs
function isValidUrl(url) {
    try {
        new URL(url);
        return true;
    } catch (error) {
        return false;
    }
}

In depth discussion about the topic here:

With that help and some trial&error it finally worked, thanks a lot!

1 Like