#csv #contentManager #request #importCsv
Please Note: This is a "base example". You will need to adjust it to your own needs.
First create a database named filesUploaded with 3 primary fields title (Text), file (Document) & mediaId (Text). This is where we will store the uploaded csv files.
Next create the database where you want to populate the items from your uploaded csv file to. For this example I have created a database named myData & I have the fields name, stock, description, email in my database. I have also created a set of data to be uploaded with the exact same column headers in my excel sheet (see image below)
Next add an After Insert Hook to the initial filesUploaded database.
Install the 'request-promise' NPM from the Wix Package Manager.
Install the 'csvtojson' NPM from the Wix Package Manager.
Your data.js file which was created after your created an After Insert Hook should look like below.
import wixData from 'wix-data';
import request from "request-promise";
import {mediaManager} from 'wix-media-backend';
const csv = require('csvtojson');
export async function filesUploaded_afterInsert(item, context) {
let url = await getFileUrl(item.mediaId);
await console.log(url);
conversion(url)
.then( (ary) => {
var i,j,temparray,chunk = 1000;
for (i=0,j=ary.length; i<j; i+=chunk) {
temparray = ary.slice(i,i+chunk);
wixData.bulkInsert("myData", temparray)
.then( (results) => {
console.log('completed batch');
})
.catch( (err) => {
console.log(err);
});
}
});
}
//------------------------------Getting File------------------------------//
function conversion(url) {
return csv()
.fromStream(request.get(url))
.then( (json) => {
return json;
});
}
//------------------------------Get URL------------------------------//
export async function getFileUrl(mediaId) {
return mediaManager.getFileUrl(mediaId);
}
On your page, have an upload button & a submit button (you can have other fields as well according to your needs)
The upload button will be used to upload the CSV so change the 'Supported File Type' to 'Document'
Create an OnClick event for your submit button and use the following code.
import wixData from 'wix-data';
export function submit_click(event) {
$w("#submit").disable();
$w("#uploadButton1").startUpload()
.then( (res) => {
let file = res.url;
let data = {
title: 'My file',
file: file,
mediaId: res.mediaId
};
wixData.insert('filesUploaded', data)
.then( (result) => {
$w("#submit").enable();
});
});
}
So basically we upload the file and then save the associated Media ID of the file so that we can retrieve a downloadable link using the Wix Media Manager Backend API.
If you are monitoring the backend console logs from your site monitoring tools then you might see the following error.
{"name":"Error","errorGroup":"User","code":"WD_REQUEST_TIMED_OUT"}
If this happens, check if your items were uploaded to the database or not because sometimes the items are indeed uploaded but still the Wix Data API throws this error.
Good luck!