1/*
2 This code comes from Vincent Lab
3 And it has a video version linked here: https://www.youtube.com/watch?v=KP_8gN8kh4Y
4*/
5
6// Import dependencies
7const fs = require("fs");
8const YAML = require("js-yaml");
9const express = require("express");
10const multer = require("multer");
11
12// Setup express
13const app = express();
14const port = 3000;
15
16// Setup Storage
17const storage = multer.diskStorage({
18 destination: function (req, file, cb) {
19 // Set the destination where the files should be stored on disk
20 cb(null, "uploads");
21 },
22 filename: function (req, file, cb) {
23 // Set the file name on the file in the uploads folder
24 cb(null, file.fieldname + "-" + Date.now());
25 },
26 fileFilter: function (req, file, cb) {
27
28 if (file.mimetype !== "text/yaml" || file.mimetype !== "text/x-yaml" || file.mimetype !== "application/x-yaml") {
29 // To reject a file pass `false` or pass an error
30 cb(new Error(`Forbidden file type`));
31 } else {
32 // To accept the file pass `true`
33 cb(null, true);
34 }
35
36 }
37});
38
39// Setup multer
40const upload = multer({ storage: storage }); // { destination: "uploads/"}
41
42// Setup the upload route
43app.post("/upload", upload.single("data"), (req, res) => {
44
45 if (req.file) {
46
47 // Get YAML or throw exception on error
48 try {
49
50 // Load the YAML
51 const raw = fs.readFileSync(`uploads/${req.file.filename}`);
52 const data = YAML.safeLoad(raw);
53
54 // Show the YAML
55 console.log(data);
56
57 // Delete the file after we're done using it
58 fs.unlinkSync(`uploads/${req.file.filename}`);
59
60 } catch (ex) {
61
62 // Show error
63 console.log(ex);
64
65 // Send response
66 res.status(500).send({
67 ok: false,
68 error: "Something went wrong on the server"
69 });
70
71 }
72
73 // Send response
74 res.status(200).send({
75 ok: true,
76 error: "File uploaded"
77 });
78
79 } else {
80
81 // Send response
82 res.status(400).send({
83 ok: false,
84 error: "Please upload a file"
85 });
86
87 }
88
89})
90
91// Start the server
92app.listen(port, () => console.log(`YAML file uploader listening at http://localhost:${port}`));
1<!--
2 This code comes from Vincent Lab
3 And it has a video version linked here: https://www.youtube.com/watch?v=KP_8gN8kh4Y
4-->
5
6<!DOCTYPE html>
7<html>
8 <head>
9 <title>YAML File Uploader</title>
10 </head>
11 <body>
12 <!-- https://code.tutsplus.com/tutorials/file-upload-with-multer-in-node--cms-32088 -->
13 <form action="http://localhost:3000/upload" enctype="multipart/form-data" method="POST">
14 <input type="file" name="data" />
15 <input type="submit" value="Upload a file" />
16 </form>
17 </body>
18</html>