Commit 18 Nodejs Wordbucket : add import function
Commits on May 6, 2018
index.js
- ทำการ install และ import fast-csv(สามารถอ่าน csv วิเคราะห์คำ และ format ที่เกี่ยวข้องได้)
- เพิ่ม function import_csv() โดยใช้ fast-csv อ่าน csv แล้วนำคำที่อ่านมา add ลง explanation database
| @@ -8,9 +8,12 @@ var Explanation = db.Explanation; |
| | |
| | //import export |
| | var fileUpload = require('express-fileupload'); |
| | -var json2csv = require('json2csv').Parser;; |
| | +var json2csv = require('json2csv').Parser; |
| | +var csv = require('fast-csv'); |
| | app.use(fileUpload()); |
| | |
| | + |
| | + |
| | var Explanation_Word = Explanation.belongsTo(Word, {as: 'Explanation_Word'}); |
| | //Word.Explanation = Word.hasMany(Explanation); |
| | |
| @@ -320,14 +323,14 @@ function export_csv(req, res, next) { //export csv |
| | |
|
| |
| | |
| | |
| | function import_csv(req, res, next) { //import csv |
| | + if (!req.files) |
| | + return res.status(400).send('No files were uploaded.'); |
| | + var csvData = []; |
| | + let uploadedCsv = req.files.csv_file.data.toString(); |
| | + var wordID_ref = Number(req.params.wordid) |
| | |
| | + csv |
| | + .fromString(uploadedCsv, { |
| | + headers: true, |
| | + ignoreEmpty: true |
| | + }) |
| | + .on("data", function(data){ |
| | + csvData.push(data); |
| | + }) |
| | + .on("end", function(){ |
| | + csvData.forEach(function(item) { |
| | + Explanation.create({ |
| | + ExplanationWordId: wordID_ref, |
| | + explanation_text: item.explanation, |
| | + like: 0, |
| | + dislike: 0, |
| | + }); |
| | + }); |
| | + }); |
| | + |
| | + return res.redirect("/word/"+wordID_ref); |
| | } |
| | |
| | // ------------------------- path and call function ------------------------- |
detail.ejs
- จาก commit 17
link เปลี่ยนชื่อเล็กน้อยเพื่อจะได้ไม่ซ้ำซ้อน
| @@ -33,7 +33,7 @@ |
| | <br> |
| | <a href="/word/<%= wordID %>/export">export</a><br><br> |
| | <form action="/word/<%= wordID %>/import" method="POST" encType="multipart/form-data"> |
| | - <input type="file" name="file" accept="*.csv" /> |
| | + <input type="file" name="csv_file" accept="*.csv" /> |
| | <input type="submit" value="Upload" /> |
| | </form> |
| | |
|
ไม่มีความคิดเห็น:
แสดงความคิดเห็น