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
*/

// Import dependencies
const fs = require("fs");
const YAML = require("js-yaml");
const express = require("express");
const multer = require("multer");

// Setup express
const app = express();
const port = 3000;

// Setup Storage
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        // Set the destination where the files should be stored on disk
        cb(null, "uploads");
    },
    filename: function (req, file, cb) {
        // Set the file name on the file in the uploads folder
        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") {
            // To reject a file pass `false` or pass an error
            cb(new Error(`Forbidden file type`));
        } else {
            // To accept the file pass `true`
            cb(null, true);
        }

    }
});

// Setup multer
const upload = multer({ storage: storage }); // { destination: "uploads/"}

// Setup the upload route
app.post("/upload", upload.single("data"), (req, res) => {

    if (req.file) {

        // Get YAML or throw exception on error
        try {

            // Load the YAML
            const raw = fs.readFileSync(`uploads/${req.file.filename}`);
            const data = YAML.safeLoad(raw);

            // Show the YAML
            console.log(data);

            // Delete the file after we're done using it
            fs.unlinkSync(`uploads/${req.file.filename}`);

        } catch (ex) {

            // Show error
            console.log(ex);

            // Send response
            res.status(500).send({
                ok: false,
                error: "Something went wrong on the server"
            });
            
        }

        // Send response
        res.status(200).send({
            ok: true,
            error: "File uploaded"
        });

    } else {

        // Send response
        res.status(400).send({
            ok: false,
            error: "Please upload a file"
        });

    }

})

// Start the server
app.listen(port, () => console.log(`YAML file uploader listening at http://localhost:${port}`));

4.13
8
Hasnohat 90 points

                                        npm install --save multer

4.13 (8 Votes)
0
0
2
Isha 105 points

                                    <!--
    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>

0
0
Are there any code examples left?
Create a Free Account
Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond.
Sign up
Develop soft skills on BrainApps
Complete the IQ Test
Relative searches
nodejs upload file locally node js make file upload node js file upload example uploading files in nodejs using filepond how to upload files to node app] node js code to upload a file uploading files with nodejs how to upload a file to a nodejs server how to upload file in project in node js nodejs uploading files upload file to folder nodejs how uploads work node js node js receive file upload How to handle file upload in nodejs file upload with node js node.js file upload Node js upload file to another server code example how to read upload files nodejs different ways of file upload in node js upload file to different server nodejs upload file to another server nodejs how to upload files in nodejs upload files using request nodejs how to upload file to an api nodejs how to upload a file to a server in node uploading files in node js how to upload file on server with node nodejs upload file to url what is node js file upload upload any file using node js file uploader nodejs upload files to server using nodejs upload a file node nodejs simple file upload server How to handle file upload in Node js? * upload file nodé how to upload file in node.js uploading a file on nodejs how to upload node js to beget node upload file to server Nodejs upload files node js upload file client upload and retrieve file to server node.js upload file to server node.js upload a file node js upload file node js how to upload files to a local nodejs server using javascript and html5 how to upload file from javascript to node where to upload my nodejs app create a file uploading nodejs server how to upload file in nodejs upload file on server node.js how to File Upload & Download in node.js How to use file upload with nodejs upload file to nodejs upload file in folder nodejs simple nodejs to handle file upload server nodejs code to upload file server uploading files nodejs how to upload file to node js how to save a file upload node uploading files in nodejs node.js upload file to server upload file from nodejs node js upload local file how to upload file in node js How would you implement a file upload in node.js? upload files to node server node.js upload files file upload in node js download and upload file in nodejs function that uploads files to node server how to upload nodejs application on server NOde.js api to upload file into server upload local file with nodejs node js how to upload a file upload file to node server node server function that uploads files to node server upload node js to server file uploading with nodejs upload file to directory nodejs how to handle upload file in nodejs Node js upload file to another server how to create a file uploader in node.js How to handle file upload in Node js upload and send a file in node.js nodejs module to upload file file upload and download with node js file upload and download with nodejs upload files on computer using nodejs node file upload example upload file with nodejs upload a file on the server nodejs upload file in nodejs upload files in node js file upload nodejs example upload file in node js How to handle file upload in Node js? node file upload how to upload node js in server html upload file node js how to upload a file in node js upload a file nodejs node and upload file how to upload node js project on server upload a file to a folder nodejs node js file upload upload file nodejs how to upload files node js where to upload node js project on server node.js upload file node js upload files simple file upload server node file upload node js upload local file in node js node upload file nodejs file upload how to upload file on another server nodejs node file upload from browser node js file uploader upload files nodejs node upload files node file uploading file upload nodejs demo file upload nodejs nodejs upload file nodejs receive file upload file uploading in node js node js upload file How to Upload Files to a Node.js Server
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source