FileUpload Mean Stack – Part 2

package.json


{
  "name": "serverfileupload",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "express-fileupload": "^1.1.6"
  }
}

app.js


var express = require('express');
var bodyParser = require('body-parser');
var fileUpload = require('express-fileupload');
const app = express();

app.use(fileUpload());
app.use(bodyParser.json());

app.get('/', (req, res, next) => {
    res.status(200).send('I am from get');
})

app.post('/upload', (req, res, next) => {

    const user = req.body;
    console.log('user : ', user);

    const file = req.files.Photo;
    console.log(file);
    console.log("file.name : ", file[0].name);

    // file.mv("./Uploads/"+file[0].name, (err, result) => {
    //     if (err) {
    //         //throw err.message
    //         res.send({
    //             Error : "true",
    //             message: err.message
    //         })
    //     }
    //     res.send({
    //         success: 'true',
    //         message: "File Uploaded !"
    //     });
    // })

    if (req.files) {
        const file = req.files.Photo;
        for (let i = 0; i < file.length; i++) {
            file[i].mv('./uploads/' + file[i].name, function (err) {
                if (err) {
                    res.send(err);
                }
            })
        }
        res.send({
            success: 'true',
            message: "File Uploaded !"
        });
    }
})


app.listen('3000', () => {
    console.log('Server Start Port : 3000');
})

Node.js Write JSON Object to File

// file system module to perform file operations
const fs = require('fs');
 
// json data
var jsonData = '{"persons":[{"name":"John","city":"New York"},{"name":"Phil","city":"Ohio"}]}';
 
// parse json
var jsonObj = JSON.parse(jsonData);
console.log(jsonObj);
 
// stringify JSON Object
var jsonContent = JSON.stringify(jsonObj);
console.log(jsonContent);
 
fs.writeFile("output.json", jsonContent, 'utf8', function (err) {
    if (err) {
        console.log("An error occured while writing JSON Object to File.");
        return console.log(err);
    }
 
    console.log("JSON file has been saved.");
});

looking-to-upload-multiple-images-with-express-fileupload

node_fileUpload

http sends you data in bits and chunks/pieces which are intended to get assembled as they reach their destination.

Body-parser parses your request and converts it to a format which you can easily extract for the relevant information

Body-parser is part of express module,Whenever install express, body-parser will be automatically instlled in your project

So, body-parser parses your incoming request, assembles the chunks containing your form data, then created this body object for you and filled it with your form data.

import body-parser

since i am passing json only, we will use bodyparser.json(), it only parse json, nothing else.

it is middleware we need to use inside the use() method

Ex : app.use(bodyparser.json())

Leave a Reply

Your email address will not be published. Required fields are marked *