Saving an image to database using code

I have the following:


export function saveButton_click(event) {

$w("#petImage").startUpload()     
    .then( (uploadedFile) => {     
    let url = uploadedFile.url;     
    session.setItem("petImage", url)     
    console.log(url); 
});

let toSavePet = {
    "profilePhoto":          session.getItem("petImage")
}
    
wixData.save("Pets", toSavePet);

}

For some reason, though, the image doesn’t save to the database. Any work arounds? I need to do it through code because other data will save to other databases with the same button click.

You need to save to the database inside of startUpload’s then() function. Something like this:

export function saveButton_click(event) {
    $w("#petImage").startUpload()
    .then((uploadedFile) => {
        let url = uploadedFile.url;
        console.log(url);
        let toSavePet = {
            "profilePhoto": url
        }
        wixData.save("Pets", toSavePet);
    });
}

Note that you don’t need to save the url in the session data storage, you can use it directly as a parameter in toSavePet.