I have a bunch of images on another server that I want to import to a collection and store the images locally on Wix.
I have the image URLs in the collection and have been trying to figure out how to import the actual images and have them associated with the right records in the colection. I found this guy’s solution online earlier: https://stackoverflow.com/questions/60860639/how-to-import-an-image-to-wix-data-collection and have been trying to make it work for me.
Here’s what I have:
a) page code
very simple…basically just calls a back-end function.
import {importImages} from 'backend/importer';
$w.onReady(function () {
importImages()
});
b) the jsw module called by the page code
This is supposed to import the images associated with the URLs in the collection, tag them with the record id so they can be connecetd later.
import wixData from 'wix-data';
import { mediaManager } from 'wix-media-backend';
export function importImages() {
wixData.query("Books")
.isEmpty("reviewImage")
.isNotEmpty("image_url")
.limit(5)
.find()
.then(result => Promise.all(result.items.map(item => {
return mediaManager.importFile('/images', item.imageUrl, {
"mediaOptions": {
"mediaType": "image"
},
"metadataOptions": {
"context": {
"itemId": item._id // <-- this is how we know which item to update later
}
}
});
})))
}
c) events.js file
this should detect files uploaded to the media manager and add the local image to the right record in the collection, based upon the meta data added above.
import wixData from 'wix-data';
export function wixMediaManager_onFileUploaded(event) {
if (event.context.itemId) {
// get where item._id === event.context.itemId
return wixData.get("Books", event.context.itemId, { suppressAuth: true })
.then(itemToUpdate => {
// set the "image" field
itemToUpdate.image = event.fileInfo.fileUrl;
return wixData.update("Books", itemToUpdate, { suppressAuth: true });
});
}
}
All very elegant as an idea but I cannot get it run…don’t think the first step of uploading the files is happening, so the function in events.js is not firing.
Can anyone diagnose what I have done wrong. I am assuming this can be run in a JSW…I fairly quickly fuigured out that you can’t do this from the front-end page code itself, so this is where I eneded up.
Simon.