I have a Wix Collection (visible in the Content Manager) called "Guests", which includes a column of type Image. I want to import a CSV file in such a way that an externally-hosted image is uploaded to Wix and saved in this field.
I can import a CSV file with the image column value set to an external URL, but the image file is not imported to Wix (i.e. the image file is fetched from the external site every time it is used).
I've tried writing a myCollection_beforeInsert()
hook to call wixMediaManager.importFile()
and use the returned fileUrl
, but Wix doesn't recognise my value as an image.
'wix:image://v1/{fileUrl}'
, Wix complains "Cell value type is Text."{ type: 'image', src: 'wix:image://v1/{fileUrl}' }
, Wix complains "Cell value type is JS Object."'wix:image://v1/{fileUrl}/{fileName}#originWidth={width}&originHeight={height}'
. I tried this but the image width and height are not returned from the importFile()
method, so it is still recognised as Text.What are my other options for setting the image field value? The docs are unclear. https://www.wix.com/corvid/reference/wix-data.html
I got this working by
First I imported a CSV with a "imageUrl" field.
Then I triggered a piece of code (I put it in a page's $w.onReady()
, but you can put it anywhere), to call importFile()
with additional context:
function importImages() {
wixData.query("myCollection")
.isEmpty("image")
.isNotEmpty("imageUrl")
.find() // max 1000 items
.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
}
}
});
}));
}
And I registered an event listener for Wix's onFileUploaded
event, to update the image field for the relevant data item.
export function wixMediaManager_onFileUploaded(event) {
if (event.context.itemId) {
// get where item._id === event.context.itemId
return wixData.get("myCollection", event.context.itemId, { suppressAuth: true })
.then(itemToUpdate => {
// set the "image" field
itemToUpdate.image = event.fileInfo.fileUrl;
return wixData.update("myCollection", itemToUpdate, { suppressAuth: true });
});
}
}