Ist es möglich, eine CSV-Datei hochzuladen und daraus Sammlungseinträge zu erstellen?JavaScript

Javascript-Forum
Guest
 Ist es möglich, eine CSV-Datei hochzuladen und daraus Sammlungseinträge zu erstellen?

Post by Guest »

Ich versuche, aus einer hochgeladenen CSV-Datei neue Sammlungseinträge zu erstellen (die Sammlung ist bereits erstellt). Ist das nur in Strapi möglich?
Bis jetzt habe ich eine Sammlung erstellt:

Code: Select all

{
"kind": "collectionType",
"collectionName": "locations",
"info": {
"singularName": "location",
"pluralName": "locations",
"displayName": "location",
"description": ""
},
"options": {
"draftAndPublish": true
},
"pluginOptions": {},
"attributes": {
"address": {
"type": "text",
"required": true
},
"country": {
"type": "string",
"required": true
},
"city": {
"type": "string",
"required": true
},
"zip": {
"type": "string",
"required": true
}
}
}
und eine einzelne Upload-Komponente, bei der ich nur das Hochladen einer CSV-Datei erlaube.

Code: Select all

{
"kind": "singleType",
"collectionName": "loactions-uploads",
"info": {
"singularName": "loactions-upload",
"pluralName": "loactions-uploads",
"displayName": "Loactions-upload"
},
"options": {
"draftAndPublish": true
},
"pluginOptions": {},
"attributes": {
"upload": {
"allowedTypes": [
"files"
],
"type": "media",
"multiple": false
}
}
}
und der lifecycles.js-Hook sieht so aus:

Code: Select all

const fs = require("fs");
const path = require("path");
const { parse } = require("csv-parse");

module.exports = {
async afterCreate(event) {
const { result } = event;
const file = result.file;
if (!file || file.ext !== ".csv") {
strapi.log.warn("No valid .csv file found.");
return;
}

const filePath = path.join(strapi.dirs.static.public, file.url);

try {
const data = fs.readFileSync(filePath, "utf-8");

// Parse CSV
const records = [];
const parser = parse({ delimiter: ";", columns: true });
parser.write(data);
parser.end();

parser.on("readable", () => {
let record;
while ((record = parser.read())) {
records.push(record);
}
});

await new Promise((resolve, reject) => {
parser.on("end", resolve);
parser.on("error", reject);
});

// Process records and create entries
for (const record of records) {
await strapi.entityService.create("api::location.location", {
data: {
zip: record.ZIP,
address: record.Address,
country: record.Country,
city: record.city,
},
});
}

strapi.log.info(
`Successfully imported ${records.length} entries from CSV.`
);
} catch (err) {
strapi.log.error("Failed to process the CSV file:", err);
}
},
};
Wenn ich die Datei hochlade, passiert nichts. Ich sehe keine neuen Einträge. Warum?
Die CSV-Datei sieht wie folgt aus:

Code: Select all

ZIP;Address;City;Country;
1010;Seilerstätte 12/1;Vienna;Austria;
1030;Rochusgasse 9/21,Vienna;Austria;

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post