User upload images to media gallery field in database.

What i’m trying to do is similar to the student submission form in the example provided by wix. A user fills out a form, uploads an image, and then submits it to a database. The difference is that I would like to submit multiple images instead of just one.

I thought it would be as simple as uploading images to a gallery and then submitting them to the database along with the other information in the form. I was wrong. The images upload to the gallery with no problem. The gallery is linked to the media gallery field in the database. When I click submit, the success message appears, the new entry appears in the database, but when I check the database the medial gallery field is empty.

In the console I also get the following error message.
Wix code SDK Warning: The items parameter of “gallery” that is passed to the items method cannot be set to null or undefined.

4 Likes

Hi,

If you use code to write the submit button, check about async functions, perhaps you are trying to submit the data before the promise return.

If not, can you please send us a URL to your site and specify the name of the page so we can inspect?

Best,
Sapir

The issue was happening without any code in the submit button.
https://viniisiggs.wixsite.com/hannashugs/sign-in
Is the URL to the site.

I’ve started work out how to do it in code but it’s slow going. The site is sitting just like when i had the error.

Thank you

what is the page name?

@sapirh Sorry, the page name is Manage

I approved your member request.

Hi,

The problem was that the program didn’t recognise the onClick() event handler of the submit button.
Export the event handler from the properties and write the code again.

Best,
Sapir

To show you what is going on I had disconnected the On Click event of the Submit button.

The first iteration of the site used the student submit form example almost verbatim. Some text boxes and an upload button for an image. The title and image were required fields. Then clicking the submit button would submit everything. It was nice and simple.

Now what i’m trying to do is have multiple images per item. I found that the database can have a media gallery field which should work for what i’m doing. As my first attempt I added a gallery to the form. The upload button got some code to be able to upload images to the gallery that is on the form. The gallery then was linked to the database media gallery field. My assumption was that when clicking submit (with no other code to it) everything would get stored in the data base. What I get is that all the text fields get stored but the images that are sitting in the gallery do not. This is core of my main question. How can I just use a simple (non code driven) submit button to store the gallery into the database. The simple submit button automates a great deal of things like displaying the “everything is stored” message, validating required fields, creating a new entry in the database, storing everything, and clearing the form when done.

Since I posted the question I’ve been working on a workaround. The code in the On Click event that you saw is my best attempt at a workaround. The two workaround ideas that I had were as follows.

  1. Use the standard submit button to store all the text fields. Don’t use the automatic “everything is stored” message. Then when the database onAfterSave event triggers, check to see if there was anything stored in the gallery. If there was, manually push the images into the databse and show “everything is stored.” If there was nothing in the gallery then delete the database entry and show “error submitting” message. This felt clunky to me because a forgetting to add an image would cause to refill out the form and entries would constantly be added and deleted. I could have a routine that would repopulat the text fields if the image check failed but again it feels clunky.

  2. Manually code the whole thing. This involves validating all the inputs and the storing them into the new database entry. This the the code you saw.

Any input one way or the other would be greatly appreciated. Thank you.

Since I haven’t found any example code on how to do this now that I finished it I wanted to post it. Disclaimer is that I am not a Javascript programmer I am much more comfortable in C so that any obvious mistakes i’m sorry about.

Here is a picture of what the page looks like. I can’t link to this for demonstration purposes because it is password protected.

Here is the code. I tried to make all the names self explanatory.

// For full API documentation, including code examples, visit Velo API Reference - Wix.com
import { session } from ‘wix-storage’;
import wixWindow from ‘wix-window’;

$w.onReady( function () {
//TODO: write your page related code here…

});

//Toggles the database boolean filed “forSale”
export function ToggleButton_click(event) {
//Retrieve the row clicked in the table.
if (session.getItem(“row”) === null ) {
//If the stored item is null show an error.
wixWindow.openLightbox(“Error”);
} else {
//If the stored item is a number good,
//set it as the current index.
$w(‘#dataset2’).setCurrentItemIndex(session.getItem(“row”))
//Get the forSale item.
let item = $w(‘#dataset2’).getCurrentItem();
//Set field value opposite of what was there.
if (item.forSale === true ) {
$w(‘#dataset2’).setFieldValue(“forSale”, false );
} else {
$w(‘#dataset2’).setFieldValue(“forSale”, true );
}
//Save the entry.
$w(‘#dataset2’).save();

} 

}

//click event insde table to set the row selected.
export function table1_rowSelect(event) {
//Clear the current session just in case.
session.clear();
//Grab the item clicked on. This is compensated for the page size and current page.
//Current page is one indexed and subtracting one makes it zero indexed.
//Current page minus one time page size give the number of database entries not shown.
//Then adding the row index give the selected row.
session.setItem(“row”, (($w(“#dataset2”).getCurrentPageIndex() - 1) * $w(“#dataset2”).getPageSize()) + event.rowIndex);
}

//Launches a light box that allows editing of an existing entry.
export function EditButton_click(event) {
//Retrieve the row clicked in the table.
if (session.getItem(“row”) === null ) {
//If the stored item is null show an error.
wixWindow.openLightbox(“Error”);
} else {
//chains together events for when the light box is closed.
//this refreshes the table to show data changes.
wixWindow.openLightbox(“Edit”).then(() => { $w(“#dataset2”).refresh() }).then(() => {
$w(“#table1”).refresh();
});
}
}

//Delets an entry from the database that was selected in the table.
export function DeleteButton_click(event) {
//Retrieve the row clicked in the table.
if (session.getItem(“row”) === null ) {
//If the stored item is null show an error.
wixWindow.openLightbox(“Error”);
} else {
//chains together events for when the light box is closed.
//this refreshes the table to show data changes.
wixWindow.openLightbox(“Delete”).then(() => { $w(“#dataset2”).refresh() }).then(() => {
$w(“#table1”).refresh();
});
}
}

//Refresh the table after saving database1.
//This event fires when a save completes.
//A completed save means there is new data to show.
export function dataset1_afterSave() {
//First refresh dataset2, this will pull new data from the database.
//The data does not autorefresh.
$w(“#dataset2”).refresh().then(() => {
//Once the new data is pulled, refresh the table.
$w(“#table1”).refresh();
});
}

//Uploads new images into the gallery. This may be used multiple times to load
//several images.
export function uploadButton_change(event) {
//Disable the submit button so that a submit does not happens
//while uploading.
$w(‘#SubmitButton’).disable();
//Beacuse everything is done manually some limits need to be set.
let uploadedImageSizeLimit = 15728640; //15MB
let databaseNumberOfImages = 10;
//The gallery might have been hidden so show it.
$w(“#gallery”).show();
//Grab the info about the selected file.
let selectedFile = $w(“#uploadButton”).value;
//Grab the size of the file.
let selectedFileSize = selectedFile[0].size;
//If the file size is less then the limit start the upload process.
if (selectedFileSize < uploadedImageSizeLimit) {
//Galleries don’t have validation like a text box.
//These items (red box and missing image text) are
//used to simulate that validation feel.
$w(“#MissingImage”).hide();
$w(“#MissingImage2”).hide();
//Hide the status text box. Since the text shown by upload button cannot
//be dirrectly controlled this avoids the file name shown on top of the txt.
$w(“#uploadStatusText”).hide();
//Start the upload and change the button label.
$w(“#uploadButton”).startUpload($w(“#uploadButton”).buttonLabel = “Uploading”)
.then((uploadedFile) => {
//Grab the URL that the file was loaded to.
let uploadfileurl = uploadedFile.url;
//Pull the existing items in the gallery.
//If the gallery was empty this just sets up the array.
let items = $w(“#gallery”).items;
//Push will append itmes to the array.
//Store the image to the array.
items.push({
“src”: uploadfileurl,
“description”: “”,
“title”: “”
});
//Now load the array with the newly appended item back into
//the gallery.
$w(“#gallery”).items = items;
//Reset the upload button.
$w(“#uploadButton”).reset();
//Change the button label back to the original one.
$w(“#uploadButton”).buttonLabel = “Add an Image”;
//Enable the delete image button because there are now
//images to delete.
$w(“#DeleteImageButton”).enable();
//Use the upload text to show the image uploaded successfully.
$w(“#uploadStatusText”).text = “Image Uploaded”;
//Now that the file name is gone, show the upload text.
$w(“#uploadStatusText”).show();
//When the max number of images is reached,
//disable the upload button.
if (items.length >= databaseNumberOfImages) {
$w(“#uploadButton”).disable();
}
//Play the gallery just in case.
$w(“#gallery”).play();
})
//If an error occures
. catch ((uploadError) => {
//Reset the upload button.
$w(“#uploadButton”).reset();
//Change the button label back to the original one.
$w(“#uploadButton”).buttonLabel = “Add an Image”;
//Use the upload text to show that a problem occured.
$w(“#uploadStatusText”).text = “File type not supported”;
//Now that the file name is gone, show the error text.
$w(“#uploadStatusText”).show();
});
} else {
//Reset the upload button.
$w(“#uploadButton”).reset();
//Use the upload text to show the max file size.
$w(“#uploadStatusText”).text = “Max FIle Size 15 MB”;
//Now that the file name is gone, show the upload text.
$w(“#uploadStatusText”).show();
}
//Enable submitt now that whatever is done.
$w(‘#SubmitButton’).enable();
}

//Store all the entered data. Validate data before storing.
export function SubmitButton_click(event) {
//Disable the Submit button to prevent multiclick.
$w(‘#SubmitButton’).disable();
//Create a flag that assumes eveything in the form is fine.
//The flag is set to false if something in the form is wrong.
let formGoodToGo = true ;

/Systematically validate all the inputs. This is done
because the sumbit happens manually. This also makes
sure that the required fields are sumbitted.
/

//Checks to see that the title is not blank.
$w(‘#TitleTextBox’).onCustomValidation((value, reject) => {
if (value === “”) {
//Something in the form is wrong.
formGoodToGo = false ;
//Set the reject text. Not sure if this is actually needed.
reject(“Blank”);
//Show the red box not that the data is invalid.
$w(‘#TitleTextBox’).updateValidityIndication();
} else {
//Reset the red box.
$w(‘#TitleTextBox’).resetValidityIndication();
}

}); 

//Checks to see that the type is not blank.
$w(‘#TypeDropdown’).onCustomValidation((value, reject) => {
if (value === “”) {
//Something in the form is wrong.
formGoodToGo = false ;
//Set the reject text. Not sure if this is actually needed.
reject(“Blank”);
//Show the red box not that the data is invalid.
$w(‘#TypeDropdown’).updateValidityIndication();
} else {
//Reset the red box.
$w(‘#TypeDropdown’).resetValidityIndication();
}

}); 

//Checks to see that the gallery is not empty.
if ($w(‘#gallery’).items.length === 0) {
//Something in the form is wrong.
formGoodToGo = false ;
//Show the red box not that the data is invalid.
//This is done manually since gallery does not have
//built in validity red box.
$w(‘#MissingImage’).show();
$w(‘#MissingImage2’).show();
} else {
//Reset the red box.
$w(‘#MissingImage’).hide();
$w(‘#MissingImage2’).hide();
}
//Check if the price entered is valid.
//A blank price is valid.
//The standard is dollars followed by 2 decimal places.
if ($w(‘#PriceTextBox’).valid === false ) {
//Something in the form is wrong.
formGoodToGo = false ;
}
//Check if the form is fine.
if (formGoodToGo === true ) {
//The form is fine, now store the data.
//When new data is pushed to the database a new entry is created automatically.
$w(‘#dataset1’).setFieldValue(“title”, $w(‘#TitleTextBox’).value);
$w(‘#dataset1’).setFieldValue(“type”, $w(‘#TypeDropdown’).value);
$w(‘#dataset1’).setFieldValue(“date”, $w(‘#datePicker1’).value);
$w(‘#dataset1’).setFieldValue(“forSale”, $w(‘#checkbox1’).checked);
$w(‘#dataset1’).setFieldValue(“price”, $w(‘#PriceTextBox’).value);
$w(‘#dataset1’).setFieldValue(“notes”, $w(‘#NotesTextBox’).value);
//Check if a Document is stored.
if (session.getItem(“Document”) !== “null”) {
//If it is, store it in the database.
$w(‘#dataset1’).setFieldValue(“patern”, session.getItem(“Document”));
}
//Grab the items from the gallery.
let items = $w(‘#gallery’).items;
//Grab the first image and store it as a thumbnail.
//The reason for the thumbnail is that a table can not display a gallery.
//The table shows the data nicly.
$w(‘#dataset1’).setFieldValue(“thumbnail”, items[0].src);
//Store the gallery.
$w(‘#dataset1’).setFieldValue(“image”, items);
//Now save the data.
$w(‘#dataset1’).save()
.then(() => {
//The save completed correctly,
//now clear the data out of the form
//and reset all parameters.
//Show the success message.
$w(‘#text18’).show();
$w(‘#TitleTextBox’).value = ‘’;
$w(‘#TypeDropdown’).value = ‘’;
let today = new Date();
$w(‘#datePicker1’).value = today;
$w(‘#checkbox1’).checked = false ;
$w(‘#PriceTextBox’).value = ‘’;
$w(‘#NotesTextBox’).value = ‘’;
while (items.length !== 0) {
items.splice(0, 1);
}
$w(‘#gallery’).items = items;
//Resetting the validity here will keep the text boxes from lighting up red.
$w(‘#TypeDropdown’).resetValidityIndication();
$w(‘#TitleTextBox’).resetValidityIndication();
//Reset the upload button.
$w(“#uploadButton2”).reset();
//Change the button label back to the original one.
$w(“#uploadButton2”).buttonLabel = “Add a Pattern”;
//Use the upload text to show the max file size.
$w(“#uploadStatusText2”).text = “Max FIle Size 35MB”;
//Now that the file name is gone, show the upload text.
$w(“#uploadStatusText2”).show();
//Reset the upload button.
$w(“#uploadButton”).reset();
//Use the upload text to show the max file size.
$w(“#uploadStatusText”).text = “Max FIle Size 15MB”;
//Now that the file name is gone, show the upload text.
$w(“#uploadStatusText”).show();
//Clear out the previously stored value of document.
session.setItem(“Document”, null );
//Disable the delete image button.
$w(‘#DeleteImageButton’).disable();
})
//If we get this far, hide the success message after 3 seconds.
.then(setTimeout( function () { $w(‘#text18’).hide(); }, 3000))
//If something goes wrong show the failure message for 3 seconds.
//I’m probably doing this wrong.
. catch (() => { $w(‘#text22’).show().then(setTimeout( function () { $w(‘#text22’).hide(); }, 3000)); })

}  **else**  { 

//If something on the form is wrong then show the failure message.
$w(‘#text22’).show().then(setTimeout( function () { $w(‘#text22’).hide(); }, 3000));
}
//Re-enable the button after the form is submitted.
$w(‘#SubmitButton’).enable();
}
//Delete the currenlty shown image.
export function DeleteImageButton_click(event) {
//We need some limits.
let databaseNumberOfImages = 10;
//Grab the current index of the image shown.
let currentItem = $w(‘#gallery’).currentIndex;
//Store the items in the gallery in an array.
let items = $w(‘#gallery’).items;
//Using splice remove the item out of the array that
//matches the index of the image.
items.splice(currentItem, 1);
//If the upload button was disabled when the
//limit of images was reached this will re-enable the button
//since an image was just deleted.
if (items.length < databaseNumberOfImages) {
$w(‘#uploadButton’).enable();
}
//Store the items back in to the gallery.
$w(‘#gallery’).items = items;
//If the number of images is zero, disable the delete button.
if (items.length === 0) {
$w(‘#DeleteImageButton’).disable(). catch ((error) => { console.log(error) });
}
}
//Loads a document.
export function uploadButton2_change(event) {
//Disable the submit button so that a submit does not happens
//while uploading.
$w(‘#SubmitButton’).disable();
//Beacuse everything is done manually some limits need to be set.
let uploadedImageSizeLimit = 36700160; //35MB
//Clear out the previously stored value.
session.setItem(“Document”, null );
//Grab the info about the selected file.
let selectedFile = $w(‘#uploadButton2’).value;
//Grab the size of the file.
let selectedFileSize = selectedFile[0].size;
//If the file size is less then the limit start the upload process.
if (selectedFileSize < uploadedImageSizeLimit) {
//Hide the status text box. Since the text shown by upload button cannot
//be dirrectly controlled this avoids the file name shown on top of the txt.
$w(“#uploadStatusText2”).hide();
//Start the upload and change the button label.
$w(“#uploadButton2”).startUpload($w(“#uploadButton2”).buttonLabel = “Uploading”)
.then((uploadedFile) => {
//Grab the URL that the file was loaded to.
let uploadfileurl = uploadedFile.url;
//Now store the URS in the session file.
session.setItem(“Document”, uploadfileurl);
//Reset the upload button.
$w(“#uploadButton2”).reset();
//Change the button label back to the original one.
$w(“#uploadButton2”).buttonLabel = “Change the Pattern”;
//Use the upload text to show the image uploaded successfully.
$w(“#uploadStatusText2”).text = “Pattern Uploaded”;
//Now that the file name is gone, show the upload text.
$w(“#uploadStatusText2”).show();
})
//If an error occures
. catch ((uploadError) => {
//Reset the upload button.
$w(“#uploadButton2”).reset();
//Change the button label back to the original one.
$w(“#uploadButton2”).buttonLabel = “Add a Pattern”;
//Use the upload text to show that a problem occured.
$w(“#uploadStatusText2”).text = “File type not supported”;
//Now that the file name is gone, show the error text.
$w(“#uploadStatusText2”).show();
});
} else {
//Reset the upload button.
$w(“#uploadButton2”).reset();
//Use the upload text to show the max file size.
$w(“#uploadStatusText2”).text = “Max FIle Size 35 MB”;
//Now that the file name is gone, show the upload text.
$w(“#uploadStatusText2”).show();
}
//Enable submitt now that whatever is done.
$w(‘#SubmitButton’).enable();
}

This is a similar page as shown about but used for editing existing entries. This is done inside a lightbox. A row is selected inside the table and then the edit button launches the lightbox.


Here is the code.

// For full API documentation, including code examples, visit Velo API Reference - Wix.com
import { session } from ‘wix-storage’;
import wixWindow from ‘wix-window’;

$w.onReady( function () {

});

export function dataset1_ready() {
$w(‘#dataset1’).setCurrentItemIndex(parseInt(session.getItem(“row”), 10)).then(() => {
//Now that the current index is changed load all the items
//into the text boxes.
let items = $w(‘#dataset1’).getCurrentItem();
$w(‘#TitleTextBox’).value = items.title;
$w(‘#TypeDropdown’).value = items.type;
$w(‘#datePicker1’).value = items.date;
$w(‘#checkbox1’).checked = items.forSale;
$w(‘#PriceTextBox’).value = items.price;
$w(‘#NotesTextBox’).value = items.notes;
$w(‘#gallery’).show().then(() => {
$w(‘#gallery’).items = items.image
//If some images were loaded enable the delete button.
if (items.image.length > 0) {
$w(‘#DeleteImageButton’).enable();
}
});
//Clear out the previously stored value for the pattern.
session.setItem(“Document”, null );
//Check to see if a pattern is stored.
//If it is enable the button and link it.
if (items.hasOwnProperty(‘patern’) === true ) {
//Grab the pattern and link it.
$w(‘#ViewPatternButton’).link = items.patern;
//Enable the button to view the pattern.
$w(‘#ViewPatternButton’).enable();
//Change the button label to reflect that a pattern exists.
$w(“#uploadButton2”).buttonLabel = “Change the Pattern”;
}

}). **catch** (error => { console.log(error, "--error") }); 

}

//Store all the entered data. Validate data before storing.
export function SaveButton_click(event) {
//Disable the Submit button to prevent multiclick.
$w(‘#SaveButton’).disable();
//Create a flag that assumes eveything in the form is fine.
//The flag is set to false if something in the form is wrong.
let formGoodToGo = true ;

/Systematically validate all the inputs. This is done
because the sumbit happens manually. This also makes
sure that the required fields are sumbitted.
/

//Checks to see that the title is not blank.
$w(‘#TitleTextBox’).onCustomValidation((value, reject) => {
if (value === “”) {
//Something in the form is wrong.
formGoodToGo = false ;
//Set the reject text. Not sure if this is actually needed.
reject(“Blank”);
//Show the red box not that the data is invalid.
$w(‘#TitleTextBox’).updateValidityIndication();
} else {
//Reset the red box.
$w(‘#TitleTextBox’).resetValidityIndication();
}

}); 

//Checks to see that the type is not blank.
$w(‘#TypeDropdown’).onCustomValidation((value, reject) => {
if (value === “”) {
//Something in the form is wrong.
formGoodToGo = false ;
//Set the reject text. Not sure if this is actually needed.
reject(“Blank”);
//Show the red box not that the data is invalid.
$w(‘#TypeDropdown’).updateValidityIndication();
} else {
//Reset the red box.
$w(‘#TypeDropdown’).resetValidityIndication();
}

}); 

//Checks to see that the gallery is not empty.
if ($w(‘#gallery’).items.length === 0) {
//Something in the form is wrong.
formGoodToGo = false ;
//Show the red box not that the data is invalid.
//This is done manually since gallery does not have
//built in validity red box.
$w(‘#MissingImage’).show();
$w(‘#MissingImage2’).show();
} else {
//Reset the red box.
$w(‘#MissingImage’).hide();
$w(‘#MissingImage2’).hide();
}
//Check if the price entered is valid.
//A blank price is valid.
//The standard is dollars followed by 2 decimal places.
if ($w(‘#PriceTextBox’).valid === false ) {
//Something in the form is wrong.
formGoodToGo = false ;
}
//Check if the form is fine.
if (formGoodToGo === true ) {
//The form is fine, now store the data.
//When new data is pushed to the database a new entry is created automatically.
$w(‘#dataset1’).setFieldValue(“title”, $w(‘#TitleTextBox’).value);
$w(‘#dataset1’).setFieldValue(“type”, $w(‘#TypeDropdown’).value);
$w(‘#dataset1’).setFieldValue(“date”, $w(‘#datePicker1’).value);
$w(‘#dataset1’).setFieldValue(“forSale”, $w(‘#checkbox1’).checked);
$w(‘#dataset1’).setFieldValue(“price”, $w(‘#PriceTextBox’).value);
$w(‘#dataset1’).setFieldValue(“notes”, $w(‘#NotesTextBox’).value);
//Check if a Document is stored. Sometimes the session data is text
//sometimes it is a value.
if (session.getItem(“Document”) !== “null”) {
//If it is, store it in the database.
$w(‘#dataset1’).setFieldValue(“patern”, session.getItem(“Document”));
}
//Grab the items from the gallery.
let items = $w(‘#gallery’).items;
//Grab the first image and store it as a thumbnail.
//The reason for the thumbnail is that a table can not display a gallery.
//The table shows the data nicly.
$w(‘#dataset1’).setFieldValue(“thumbnail”, items[0].src);
//Store the gallery.
$w(‘#dataset1’).setFieldValue(“image”, items);
//Now save the data.
$w(‘#dataset1’).save()
.then(() => {
//The save completed correctly,
//now clear the data out of the form.
//Show the success message.
$w(‘#text18’).show();
$w(‘#TitleTextBox’).value = ‘’;
$w(‘#TypeDropdown’).value = ‘’;
let today = new Date();
$w(‘#datePicker1’).value = today;
$w(‘#checkbox1’).checked = false ;
$w(‘#PriceTextBox’).value = ‘’;
$w(‘#NotesTextBox’).value = ‘’;
while (items.length !== 0) {
items.splice(0, 1);
}
$w(‘#gallery’).items = items;
//Resetting the validity here will keep the text boxes from lighting up red.
$w(‘#TypeDropdown’).resetValidityIndication();
$w(‘#TitleTextBox’).resetValidityIndication();
//Reset the upload button.
$w(“#uploadButton2”).reset();
//Change the button label back to the original one.
$w(“#uploadButton2”).buttonLabel = “Add a Pattern”;
//Use the upload text to show the max file size.
$w(“#uploadStatusText2”).text = “Max FIle Size 35 MB”;
//Now that the file name is gone, show the upload text.
$w(“#uploadStatusText2”).show();
//Clear out the previously stored value of document.
session.setItem(“Document”, null );
})
//If we get this far, hide the success message after 3 seconds.
.then(setTimeout( function () { wixWindow.lightbox.close(); }, 3000))
//If something goes wrong show the failure message for 3 seconds.
//I’m probably doing this wrong.
. catch (() => { $w(‘#text22’).show().then(setTimeout( function () { $w(‘#text22’).hide(); }, 3000)); })

}  **else**  { 

//If something on the form is wrong then show the failure message.
$w(‘#text22’).show().then(setTimeout( function () { $w(‘#text22’).hide(); }, 3000));
}
//Re-enable the button after the form is submitted.
$w(‘#SaveButton’).enable();
}
export function CancelButton_click(event) {
wixWindow.lightbox.close();
}

//Delete the currenlty shown image.
export function DeleteImageButton_click(event) {
//We need some limits.
let databaseNumberOfImages = 10;
//Grab the current index of the image shown.
let currentItem = $w(‘#gallery’).currentIndex;
//Store the items in the gallery in an array.
let items = $w(‘#gallery’).items;
//Using splice remove the item out of the array that
//matches the index of the image.
items.splice(currentItem, 1);
//If the upload button was disabled when the
//limit of images was reached this will re-enable the button
//since an image was just deleted.
if (items.length < databaseNumberOfImages) {
$w(‘#uploadButton’).enable();
}
//Store the items back in to the gallery.
$w(‘#gallery’).items = items;
//If the number of images is zero, disable the delete button.
if (items.length === 0) {
$w(‘#DeleteImageButton’).disable(). catch ((error) => { console.log(error) });
}
}

//Uploads new images into the gallery. This may be used multiple times to load
//several images.
export function uploadButton_change(event) {
//Disable the save button so that a submit does not happens
//while uploading.
$w(‘#SaveButton’).disable();
//Beacuse everything is done manually some limits need to be set.
let uploadedImageSizeLimit = 15728640; //15MB
let databaseNumberOfImages = 10;
//The gallery might have been hidden so show it.
$w(“#gallery”).show();
//Grab the info about the selected file.
let selectedFile = $w(“#uploadButton”).value;
//Grab the size of the file.
let selectedFileSize = selectedFile[0].size;
//If the file size is less then the limit start the upload process.
if (selectedFileSize < uploadedImageSizeLimit) {
//Galleries don’t have validation like a text box.
//These items (red box and missing image text) are
//used to simulate that validation feel.
$w(“#MissingImage”).hide();
$w(“#MissingImage2”).hide();
//Hide the status text box. Since the text shown by upload button cannot
//be dirrectly controlled this avoids the file name shown on top of the txt.
$w(“#uploadStatusText”).hide();
//Start the upload and change the button label.
$w(“#uploadButton”).startUpload($w(“#uploadButton”).buttonLabel = “Uploading”)
.then((uploadedFile) => {
//Grab the URL that the file was loaded to.
let uploadfileurl = uploadedFile.url;
//Pull the existing items in the gallery.
//If the gallery was empty this just sets up the array.
let items = $w(“#gallery”).items;
//Push will append itmes to the array.
//Store the image to the array.
items.push({
“src”: uploadfileurl,
“description”: “”,
“title”: “”
});
//Now load the array with the newly appended item back into
//the gallery.
$w(“#gallery”).items = items;
//Reset the upload button.
$w(“#uploadButton”).reset();
//Change the button label back to the original one.
$w(“#uploadButton”).buttonLabel = “Add an Image”;
//Enable the delete image button because there are now
//images to delete.
$w(“#DeleteImageButton”).enable();
//Use the upload text to show the image uploaded successfully.
$w(“#uploadStatusText”).text = “Image Uploaded”;
//Now that the file name is gone, show the upload text.
$w(“#uploadStatusText”).show();
//When the max number of images is reached,
//disable the upload button.
if (items.length >= databaseNumberOfImages) {
$w(“#uploadButton”).disable();
}
//Play the gallery just in case.
$w(“#gallery”).play();
})
//If an error occures
. catch ((uploadError) => {
//Reset the upload button.
$w(“#uploadButton”).reset();
//Change the button label back to the original one.
$w(“#uploadButton”).buttonLabel = “Add an Image”;
//Use the upload text to show that a problem occured.
$w(“#uploadStatusText”).text = “File type not supported”;
//Now that the file name is gone, show the error text.
$w(“#uploadStatusText”).show();
});
} else {
//Reset the upload button.
$w(“#uploadButton”).reset();
//Use the upload text to show the max file size.
$w(“#uploadStatusText”).text = “Max FIle Size 15 MB”;
//Now that the file name is gone, show the upload text.
$w(“#uploadStatusText”).show();
}
//Enable save now that whatever is done.
$w(‘#SaveButton’).enable();
}

//Loads a document.
export function uploadButton2_change(event) {
//Disable the save button so that a submit does not happens
//while uploading.
$w(‘#SaveButton’).disable();
//Beacuse everything is done manually some limits need to be set.
let uploadedImageSizeLimit = 36700160; //35MB
//Clear out the previously stored value.
session.setItem(“Document”, null );
//Grab the info about the selected file.
let selectedFile = $w(‘#uploadButton2’).value;
//Grab the size of the file.
let selectedFileSize = selectedFile[0].size;
//If the file size is less then the limit start the upload process.
if (selectedFileSize < uploadedImageSizeLimit) {
//Hide the status text box. Since the text shown by upload button cannot
//be dirrectly controlled this avoids the file name shown on top of the txt.
$w(“#uploadStatusText2”).hide();
//Start the upload and change the button label.
$w(“#uploadButton2”).startUpload($w(“#uploadButton2”).buttonLabel = “Uploading”)
.then((uploadedFile) => {
//Grab the URL that the file was loaded to.
let uploadfileurl = uploadedFile.url;
//Now store the URS in the session file.
session.setItem(“Document”, uploadfileurl);
//Reset the upload button.
$w(“#uploadButton2”).reset();
//Change the button label back to the original one.
$w(“#uploadButton2”).buttonLabel = “Change the Pattern”;
//Use the upload text to show the image uploaded successfully.
$w(“#uploadStatusText2”).text = “Pattern Uploaded”;
//Now that the file name is gone, show the upload text.
$w(“#uploadStatusText2”).show();
//Grab the pattern and link it.
$w(‘#ViewPatternButton’).link = uploadfileurl;
//Enable the button to view the pattern.
$w(‘#ViewPatternButton’).enable();
})
//If an error occures
. catch ((uploadError) => {
//Reset the upload button.
$w(“#uploadButton2”).reset();
//Change the button label back to the original one.
$w(“#uploadButton2”).buttonLabel = “Add a Pattern”;
//Use the upload text to show that a problem occured.
$w(“#uploadStatusText2”).text = “File type not supported”;
//Now that the file name is gone, show the error text.
$w(“#uploadStatusText2”).show();
});
} else {
//Reset the upload button.
$w(“#uploadButton2”).reset();
//Use the upload text to show the max file size.
$w(“#uploadStatusText2”).text = “Max FIle Size 35 MB”;
//Now that the file name is gone, show the upload text.
$w(“#uploadStatusText2”).show();
}
//Enable save now that whatever is done.
$w(‘#SaveButton’).enable();
}

That is a huge code. 1) Is it working for you? 2) How slow is the uploading with this?

@jeff-haskins It could have probably been done in less lines of code but I wanted to be complete. The code section for editing is nearly identical to that of submitting a new entry.

  1. Yes it is working. At the very least my wife has not found any bugs.
  2. It takes 10 to 30 seconds to upload a photo depending on the size.

Let me know if you have any other questions.

I have code very similar to this but I’m having an issue with the users images missing when I access them in the database. I posted a question on the forum but havent had a reply yet. Have you had any issues in the past where the users images would disappear if you opened up their media gallery?

No I have not had any issues. Are you sure that the images are making it in? How are you storing them? How are you displaying them? Are you sure that the database has correct permissions?

@ viniisiggs
I’m trying to extract out from your code only the bit which limits the number of images that a single user can upload in a single session (let’s say 2). I know I need to use session from wix-storage, but as I’m not heavy on coding, I couldn’t make it right.
Currently an upload to a ‘Wix Pro Gallery’ is being made via an ‘upload button’ and a ‘button’ which inserts the single uploaded image into a Dataset. Any idea how this could be done via parts of your code? Here’s the part of my code which does the upload:

Import wixData from ‘wix-data’;
export function checkbox1_change(event, $w) { //ensures T&Cs box is ticked, otherwise ‘Upload’ button is disabled.
if ($w(“#checkbox1”).checked=== true ){
$w(“#button1”).enable();
$w(“#dataset1”).setFieldValue(“agreedTCs”, true );
$w(“#dataset1”).save();
}
if ($w(“#checkbox1”).checked=== false ){
$w(“#button1”).disable();
}
}
export function button1_click_1(event) { //Upload button to select a photo
if ($w(“#uploadButton1”).value.length > 0) {
$w(“#text19”).text = Uploading ${$w("#uploadButton1").value[0].name};
setTimeout( function () {
// $w(“#text19”).text = “Almost there… "
});
$w(”#uploadButton1").startUpload()
.then( (uploadedFile) => {
$w(“#text19”).text = “Upload successful”;
let toInsert = {
“pic”: uploadedFile.url
};

wixData.insert(“DD”, toInsert)
//Inserting the uploaded photo into the DB
.then( (results) => {
let item = results;
}).then(()=>{
$w(“#dataset1”).refresh();

});
})
. catch ( (uploadError) => {
$w(“#text19”).text = “File upload error”;
console.log(File upload error: ${uploadError.errorCode});
console.log(uploadError.errorDescription);
} );

Thanks

There is a single line of code in my code that you would need to change.
let databaseNumberOfImages = 10;
Change that to 2 and that would limit how many images can be uploaded.
P.S. without knowing the many many look and feel constraints that you may have it is difficult to make any recommendations further than that.

@ viniisiggs
Cool. So basically if I want to limit it on a session-basis, it will need then to be integrated with the ‘session’ storage type? Hence I need to use the session.setItem(“key”, “value”) before setting up the limitation?

Back to I don’t know all your wants and limitations. I hard coded the size of the gallery to an arbitrary 10. You could hard code it to 2. If you want the size to be variable you could pass it in with something like storage and then assign it to the size limit.

@ viniisiggs
Understood, but as I’m very light on coding I’m trying to figure out how to put it within my code linked together with the session mgmt and in which order. I don’t want to limit the DB completely, but only per session.

For limiting number of uploads per session (*didn’t include file upload/reset upload button) then to my understanding I need to capture those lines? Anything I missed?

import { session } from ‘wix-storage’;
session.setItem(“key”, “value”)

let databaseNumberOfImages = 2;
if (items.length >= databaseNumberOfImages) {
$w(“#uploadButton”).disable();