Upload Image using Code

Hi guys, please I am having troubles uploading an image to my collection using code, please does any one have the correct code? Thanks in advance

With code requests I advise to add snippets of your current attempt so we can assist in debugging.

How are you attempting to do it?

I would check out this reference for using the upload button in code,

Okay here, is my code:

let hold
export function button1_click(event) {
if ($w(“#uploadButton1”).value.length > 0) { // user chose a file
console.log(Uploading '${$w("#uploadButton1").value[0].name}');
$w(“#uploadButton1”).startUpload()
.then( (uploadedFile) => {
hold = uploadedFile.url;
$w(“#input9”).value = uploadedFile.url;
console.log(“Upload successful. File is available here:”);
console.log(uploadedFile.url);
} )
. catch ( (uploadError) => {
console.log(File upload error: ${uploadError.errorCode});
console.log(uploadError.errorDescription);
} );
}
else { // user clicked button but didn’t chose a file
console.log(“Please choose a file to upload.”)
}

let toInsert = {
“locId”: $w(“#input8”).value,
“firstName”: $w(“#input1”).value,
“email”: $w(“#input3”).value,
“qwezzy”: $w(“#input2”).value,
“questionDuringLesson”: $w(“#input4”).value,
“subject”: $w(“#dropdown1”).value,
“grade”: $w(“#dropdown2”).value,// wixUsers.currentUser.id,
“relatedResource”: $w(“#input5”).value,
“attachment”: hold,
//“contributionToQwezzy”: $w(“#switch1”).value,
“attachmentAvailable”: tru,
“date”: $w(“#datePicker1”).value
};

wixData.insert(“Qwezzy_Share”, toInsert)
.then( (results) => {
let item = results; //see item below

} )
$w(“#text18”).show()
wixLocation.to(“/thank-you”)

. catch ( (err) => {
let errorMsg = err;
} );

}

Pretty hard to read like this, screen shots work better due to having a decent looking layout if the code and errors etc. however for starters the insert seems to be outside the promise, this would mean it is

  1. starting upload
  2. Inserting record
  3. finishing upload
  4. Assigning the URL of the file to the variable

You need to put the insert statement within the .then of the button upload this way it will run AFTER the upload has finished.

Okay thanks, here is the screenshot

Yes so your issues is what I noted above. Your insert is happening before the file is uploaded so you don’t have a URL to upload.

Okay thanks, should the field type in the collection be set to “URL” or Document?

Neither. It should be Image.

Also, is there any particular reason why you are manually inserting all the information into the database collection instead of just connecting via dataset?

(If your goal is to redirect a person after the information is saved … you could use the onAfterSave when using a dataset … https://www.wix.com/corvid/reference/wix-dataset.Dataset.html#onAfterSave . )