Most Popular Tutorials
Most Popular Tutorials :-

Simply Easy Learning at Your Fingertips. Click Tutorials Menu to view More Tutorial List





Upload single and multiple files in Node.Js

DiskStorage

The disk storage engine gives you full control over storing files to disk. We will create a storage object using the diskStorage() method.

File Name :

var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, './uploads');
},
filename: function (req, file, cb) {
cb(null , file.originalname);
}
});

###################### OR ######################

var storage = multer.diskStorage({
destination: (req, file, callBack) => {
callBack(null, './public/images/')
},
filename: (req, file, callBack) => {
callBack(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
})

Here we use two function destination and filename.

  • Destination :- destination is directory where files are stored. If no destination is given, the operating system's default directory for temporary files is used. It is mandatory to create a destination directory for files store. if you are using destination as a string, multer will make sure that the directory is created for you.
  • filename - It is used to determine what the file should be named inside the folder. If you don't provide any filename, each file will be given a random name without any file extension. It is your responsibility to provide a function that should return a complete filename with a file extension. Both these functions take 3 arguments - the request object, the file object and a callback function (here, cb is callback function).
  • The 2 arguments to cb are:

  • null :- don’t want to show any error.
  • file.originalname :- we have used the same name of the file as they were uploaded.
  • Other Options :-

    limits :- You can set a limit on the size of the file that is being uploaded.
    const upload = multer({
    storage: storage,
    limits : {fileSize : 2000000},

    // limits: { fileSize: 1 * 1024 * 1024 }, // 1MB fileFilter: (req, file, cb) => {
    if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
    cb(null, true);
    } else {
    cb(null, false);
    const err = new Error('Only .png, .jpg and .jpeg format allowed!')
    err.name = 'ExtensionError'
    return cb(err);
    }
    }, });
    fileSize is in bytes. (2000000 bytes = 2MB)

    fileFilter :-

    fileFilter function to control which files should be uploaded and Not.

    File Name :

    function fileFilter (req, file, cb) {
    // To reject this file pass `false`, like so:
    cb(null, false);
    // To accept the file pass `true`, like so:
    cb(null, true);
    // You can always pass an error if something goes wrong:
    cb(new Error('I don\'t have a clue!'));
    }

    Example

    File Name :

    function fileFilter (req, file, cb) {
    // Extensio of file Allowed
    const filetypes = /jpeg|jpg|png|gif/;

    // Check extension
    const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
    // Check mimetype
    const mimetype = filetypes.test(file.mimetype);

    if(mimetype && extname){
    return cb(null,true);
    } else {
    cb('Error: Only Images!');
    }
    }

    Uploading Multiple Files using multer

    function .arrays('fieldname',max_count) that accepts an array of files, all with the name fieldname. It generates an error if more than max_count files are uploaded. The array of files will be stored in req.files.

    File Name :

    app.post("/images_upload", upload.array("my_files", 10), (req, res) =>{
    try {
    res.send(req.files);
    } catch (error) {
    console.log(error);
    res.send(400);
    }
    });

    File Name :

    // Use of Multer
    var storage = multer.diskStorage({
    destination: (req, file, callBack) => {
    callBack(null, './public/images/')
    //callBack(null, path.join(__dirname, './images/'))

    },
    filename: (req, file, cb) => {
    cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
    // cb(null, file.fieldname + '-' + Date.now() + file.originalname.match(/\..*$/)[0])
    }
    })
    var upload = multer({ storage: storage }); // for single file upload
    // var upload = multer({ storage : storage }).array('userPhoto',10); // for multiple file upload

    // ########## multiple file upload start ###############
    router.get('/upload-multiple-files', function(req,res){
    res.render('upload-multiple-file', {title: 'Upload Multiple files'})
    })
    router.post('/upload_multiple', upload.array('resume',10), (req, res) => {
    var file = req.files;
    console.log(file);
    if(file.length > 0 )
    {
    console.log("yes");
    }
    else{
    console.log("no");
    }

    res.redirect('/users/upload-multiple-files');
    });
    // ############ multiple file upload end. ##################

    Single file upload

    File Name :

    router.post('/save_user', upload.single('resume'), function(req, res, next){
    // router.post('/save_user', function(req, res, next){

    if (!req.file) {
    console.log("File not uploaded!");
    }
    else
    {
    var file_neme = req.file.filename;
    // console.log(req.file.filename)
    }

    /* upload(req,res,function(err) {
    if(err) {
    // return res.end("Error uploading multiple file.");
    console.log("File not uploaded!");
    }
    var file_neme = req.file.filename;
    // res.end("multiple File is uploaded");
    });
    */

    })

    File Name :

    const storage = multer.diskStorage({
    destination: function (req, file, cb) {
    cb(null, '/tmp/my-uploads')
    },
    filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    cb(null, file.fieldname + '-' + uniqueSuffix)
    }
    })

    File Name :

    .single(fieldname)
    Accept a single file with the name fieldname. The single file will be stored in req.file.

    .array(fieldname[, maxCount])
    Accept an array of files, all with the name fieldname. Optionally error out if more than maxCount files are uploaded. The array of files will be stored in req.files.

    .fields(fields)
    Accept a mix of files, specified by fields. An object with arrays of files will be stored in req.files.
    .none()
    Accept only text fields. If any file upload is made, error with code "LIMIT_UNEXPECTED_FILE" will be issued.

    .any()
    Accepts all files that comes over the wire. An array of files will be stored in req.files.

    uploading multiple files

    File Name :

    router.post('/upload_multiple', upload.array('resume',10), (req, res) => {
    var file = req.files;
    // console.log(file);
    if(file.length > 0 )
    {
    for(i = 0; i < file.length; i++)
    {
    const docname = req.files[i];
    console.log(docname.filename);
    }

    }
    else{
    console.log("no");
    }

    res.redirect('/users/upload-multiple-files');
    });





    Previous Next


    Trending Tutorials




    Review & Rating

    0.0 / 5

    0 Review

    5
    (0)

    4
    (0)

    3
    (0)

    2
    (0)

    1
    (0)

    Write Review Here