Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

file uploading node.js


//<html>
  //<head>
    //<title> File Uploader</title>
  //</head>
  //<body>
//<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>

//Middleware

var multer = require("multer");
var storage = multer.diskStorage({
    destination: function (req, file, callback) {
      callback(null, "/media/uploads/");
    },
    filename: function (req, file, callback) {
      var actualFileName = file.originalname;

      var actualFileNameSplit = actualFileName.split(".");

      var actualFileName0 = actualFileNameSplit[0];

      var id =
        Date.now() +
        "-" +
        actualFileName0 +
        "-" +
        path.extname(file.originalname);
      var finalId = id.replace(/s/g, "");
      callback(null, finalId);
    },
  });

// var maxSize = 200 * 1024 * 1024;
  var upload = multer({
    storage: storage,
    // limits: { fileSize: maxSize },
  }).single("file");
  // req.file is the `file` file
  // req.body will hold the text fields, if there were any
  upload(req, res, function (err) {
    if (err instanceof multer.MulterError) {
      // A Multer error occurred when uploading.

      return res.status(500).send({
        message: "Error",
        statusCode: "500",
      });
    } else if (err) {
      // An unknown error occurred when uploading.
      return res.status(500).send({
        message: "Error",
        statusCode: "500",
      });
    } else {
       return res.status(200).send({
        message: "File Uploaded!",
        statusCode: "200",
      });
      
    }
Comment

file upload in node js

const multer = require('multer');


const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads/')
    },
    filename: function(req, file, cb){
        cb(null, file.fieldname + '-'+ file.originalname+ '-' +  Date.now())
    }
});

const upload = multer({storage:storage})
Comment

Node.js Upload Files

// create upload form

var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
  res.write('<input type="file" name="filetoupload"><br>');
  res.write('<input type="submit">');
  res.write('</form>');
  return res.end();
}).listen(8080);

// parse upload file

var http = require('http');
var formidable = require('formidable');

http.createServer(function (req, res) {
  if (req.url == '/fileupload') {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
      res.write('File uploaded');
      res.end();
    });
  } else {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
    res.write('<input type="file" name="filetoupload"><br>');
    res.write('<input type="submit">');
    res.write('</form>');
    return res.end();
  }
}).listen(8080);

// save file

var http = require('http');
var formidable = require('formidable');
var fs = require('fs');

http.createServer(function (req, res) {
  if (req.url == '/fileupload') {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
      var oldpath = files.filetoupload.filepath;
      var newpath = 'C:/Users/Your Name/' + files.filetoupload.originalFilename;
      fs.rename(oldpath, newpath, function (err) {
        if (err) throw err;
        res.write('File uploaded and moved!');
        res.end();
      });
 });
  } else {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
    res.write('<input type="file" name="filetoupload"><br>');
    res.write('<input type="submit">');
    res.write('</form>');
    return res.end();
  }
}).listen(8080);
Comment

file upload in node js

const multer = require('multer');


const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads/')
    },
    filename: function(req, file, cb){
        cb(null, file.fieldname + '-'+ file.originalname+ '-' +  Date.now())
    }
});

const upload = multer({storage:storage})
Comment

Upload files in node

    npm install --save multer
Comment

file uploading node.js

//<html> 
  //<head><title> NodeJS File Upload Example </title></head> 
  //<body>
    //<form action="http://localhost:80/upload" method="post" enctype="multipart/form-data">
    
     // <input type="file" name="fileupload">
      //<br>
      //<input type="submit">
    //</form>
  //</body> 
//</html>


let http = require('http');
let formidable = require('formidable');
let fs = require('fs');

http.createServer(function (req, res) {

  //Create an instance of the form object
  let form = new formidable.IncomingForm();

  //Process the file upload in Node
  form.parse(req, function (error, fields, file) {
    let filepath = file.fileupload.filepath;
    let newpath = 'C:/upload-example/';
    newpath += file.fileupload.originalFilename;

    //Copy the uploaded file to a custom folder
    fs.rename(filepath, newpath, function () {
      //Send a NodeJS file upload confirmation message
      res.write('NodeJS File Upload Success!');
      res.end();
    });
  });

}).listen(80);
Comment

upload local file nodejs

const FormData = require('form-data');
const fetch = require('node-fetch');

function uploadImage(imageBuffer) {
  const form = new FormData();
  form.append('file', imageBuffer, {
    contentType: 'image/jpeg',
    filename: 'dummy.jpg',
  });
  return fetch(`myserver.cz/upload`, { method: 'POST', body: form })
};
Comment

how to upload file in node js

router.post('/upload', function(req, res) {
    
    let valid_response = {
        status: true
    };

    if (!req.files || Object.keys(req.files).length === 0) {
        valid_response['status'] = false;
        valid_response['message'] = 'No files were uploaded.';

        return res.status(400).send(valid_response);
    }

    // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
    let sampleFile = req.files.file;

    // Use the mv() method to place the file somewhere on your server
    sampleFile.mv(__dirname + '/../media/' + sampleFile.name, function(err) {
        if (err)
            return res.status(500).send(err);

        valid_response['file'] = sampleFile.name;
        valid_response['file_type'] = sampleFile.mimetype;
        return res.send(valid_response);
    });
});
Comment

upload file in node

Multer uploading Node
Comment

PREVIOUS NEXT
Code Example
Javascript :: call bind apply in javascript 
Javascript :: Access to localhost from other machine - Angular 
Javascript :: arrow expression javascript 
Javascript :: angular cli command to create component without spec 
Javascript :: how to set width 100 react native 
Javascript :: moment js remove seconds 
Javascript :: upload image with react 
Javascript :: js pow function 
Javascript :: JavaScript (SMonkey 60.2.3) sample 
Javascript :: how to add prefix to a string in javascript 
Javascript :: .net core json store data type in model oracle 
Javascript :: get latest input by .each jquery 
Javascript :: p cannot appear as a descendant of p react 
Javascript :: java script layout engine error 
Javascript :: JavaScript Precision Problems 
Javascript :: javascript Access Set Elements 
Javascript :: javascript Duplicating a parameter name is not allowed 
Javascript :: socket io join multiple rooms 
Javascript :: jquery callback functions 
Javascript :: How to add pop-up confirmation in angular typescript. 
Javascript :: use anchor element to open file 
Javascript :: find minimum 
Javascript :: phaser mixed animation 
Javascript :: generate random email account javascript 
Javascript :: js undici fetch stream data 
Javascript :: function Tom(a, b) { return a + b; } 
Javascript :: javascript detect if browser is not google chrome 
Javascript :: react native countdown 
Javascript :: module.exports equivalent typescript 
Javascript :: Remove escape characters from JSON Data 
ADD CONTENT
Topic
Content
Source link
Name
1+9 =