node and upload file code example
Example 1: How to Upload Files to a Node.js Server
const fs = require("fs");
const YAML = require("js-yaml");
const express = require("express");
const multer = require("multer");
const app = express();
const port = 3000;
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "uploads");
},
filename: function (req, file, cb) {
cb(null, file.fieldname + "-" + Date.now());
},
fileFilter: function (req, file, cb) {
if (file.mimetype !== "text/yaml" || file.mimetype !== "text/x-yaml" || file.mimetype !== "application/x-yaml") {
cb(new Error(`Forbidden file type`));
} else {
cb(null, true);
}
}
});
const upload = multer({ storage: storage });
app.post("/upload", upload.single("data"), (req, res) => {
if (req.file) {
try {
const raw = fs.readFileSync(`uploads/${req.file.filename}`);
const data = YAML.safeLoad(raw);
console.log(data);
fs.unlinkSync(`uploads/${req.file.filename}`);
} catch (ex) {
console.log(ex);
res.status(500).send({
ok: false,
error: "Something went wrong on the server"
});
}
res.status(200).send({
ok: true,
error: "File uploaded"
});
} else {
res.status(400).send({
ok: false,
error: "Please upload a file"
});
}
})
app.listen(port, () => console.log(`YAML file uploader listening at http://localhost:${port}`));
Example 2: How to Upload Files to a Node.js Server
<!--
This code comes from Vincent Lab
And it has a video version linked here: https://www.youtube.com/watch?v=KP_8gN8kh4Y
-->
<!DOCTYPE html>
<html>
<head>
<title>YAML File Uploader</title>
</head>
<body>
<!-- https://code.tutsplus.com/tutorials/file-upload-with-multer-in-node--cms-32088 -->
<form action="http://localhost:3000/upload" enctype="multipart/form-data" method="POST">
<input type="file" name="data" />
<input type="submit" value="Upload a file" />
</form>
</body>
</html>