1

I am trying to upload a file in nodejs using express and multer.

index.js

var mysql=require('mysql');
var session = require('express-session');
var multer=require('multer');
var express=require('express');
var path=require('path');
var cors=require('cors');
var nodemailer=require('nodemailer');
var fileupload=require('express-fileupload');
var fs=require('fs');
const app=express();
app.use(cors());
app.use(fileupload());
var bodyParser=require('body-parser');
app.use(bodyParser.json({limit: '5mb'}));
app.use(bodyParser.urlencoded({limit: '5mb',extended:true}));
require('./routes.js')(app,mc,fs,multer);
app.listen(8080,function() {
        console.log('port listening on 8080');
})

routes.js

module.exports=function(app,mc,fs,multer) {
    var storages = multer.diskStorage({
    destination: function(req, file, callback) {
        callback(null, './uploads')
    },
    filename: function(req, file, callback) {
        console.log(file)
        callback(null, file.fieldname + '-' + Date.now() + 
    path.extname(file.originalname))
    }
    })

app.post('/reactTest',function(req,res) {

    var uploads = multer({
        storage: storages,
        fileFilter: function(req, file, callback) {
            var ext = path.extname(file.originalname);
            if (ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') {
                res.send('Only images are allowed');
            }
            else {
                fs.exists('./uploads/'+file.originalname, function(exists) {    
                    console.log(exists);
                    if(exists) {
                        res.send('images already uploaded');
                    }
                    else {  
                        callback(null, true);
                    }
                })
            }   
        }
    }).single('user.uploadContent');
    uploads(req, res, function(err) {
        console.log(req.body);
        res.send('File is uploaded');
    })

})
    app.get('/',function(req,res) {
        var localTutor=require('./child.js');
        localTutor.NodeTutorial()();
        res.writeHead(200,{'Content-Type':'text/html'});
        res.write('<form action="fileUpload" method="post" enctype="multipart/form-data">');
        res.write('<input type="file" name="files" >');
        res.write('<br><input type="submit" >');
        res.write('</form>');
        res.send();
        //return res.send({error:true,message:'working'});
            //res.render('html');
    })
    app.post('/fileUpload',function(req,res) {

        var uploads = multer({
            storage: storages
        }).single('files');
        uploads(req, res, function(err) {
            if(err) {
                throw err;
            }
            return res.send({status:'file uploaded'});
        })
    })

}

front-end

handleSubmit=(values,event)=> {
        console.log(values);
        const forms=new FormData(event.target);
        let promise=fetch('http://localhost:8080/reactTest', {
                method:'POST',
                mode:'CORS',
                body:forms,
                headers:{

                }

        }).then(res =>res.json()).then(result=>console.log(result)) 

    }

when i uploaded a file it returns status as "file uploaded", but the file is doesn't uploaded to the directory.I don't know what the issue here is? I am also attaching the code to create a restful api at front-end side.

4
  • do you check your upload folder have correct permission? Commented Mar 26, 2018 at 7:39
  • ya its having all permission. Commented Mar 26, 2018 at 7:40
  • 1
    maybe fileupload module conflict with multer? Commented Mar 26, 2018 at 8:07
  • 'path' is not defined Commented Mar 26, 2018 at 8:15

1 Answer 1

1

as @wdetac said , remove app.use(fileupload()); then add var path=require('path'); to your routes.js file

a working example

views/index.ejs

<form action="fileUpload" method="post" enctype="multipart/form-data" 
id="form-id">
    <input type="file" id="file-select" name="files" multiple/><br/>
    <input type="text" name="email" id="email"><br>
    <button type="submit" id="upload-button">Upload</button>
</form>

<script>

var form = document.getElementById('form-id');
var fileSelect = document.getElementById('file-select');
var uploadButton = document.getElementById('upload-button');

form.onsubmit = function(event) {
  event.preventDefault();


  var files = fileSelect.files;
  var formData = new FormData();
  for (var i = 0; i < files.length; i++) {
      var file = files[i];

      if (!file.type.match('image.*')) {
        continue;
      }

      formData.append('files', file, file.name);
    }
    var email = document.getElementById('email').value;
    formData.append('email',email);
    let promise=fetch('http://localhost:8080/reactTest', {
                method:'POST',
                mode:'CORS',
                body:formData

        }).then(res =>res.json()).then(result=>console.log(result)) 
}

</script>

routes.js

    app.post('/reactTest',function(req,res) {

    var uploads = multer({
        storage: storages,
        fileFilter: function(req, file, callback) {
            var ext = path.extname(file.originalname);
            if (ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') {
                res.send('Only images are allowed');
            }
            else {
                fs.exists('uploads/'+file.originalname, function(exists) {    
                    console.log(exists);
                    if(exists) {
                        res.send('images already uploaded');
                    }
                    else {  
                        callback(null, true);
                    }
                })
            }   
        }
    }).single('files');
    uploads(req, res, function(err) {
        console.log('----------',req.body);
        res.send('File is uploaded');
    })

})
Sign up to request clarification or add additional context in comments.

8 Comments

how can i retrieve form data object when i remove the app.use(fileupload()) ?
you can access to it by 'req.file' 'uploads(req, res, function(err) { console.log(req.file);'
ok.But I am also appending some other contents to the form data object.How can i retreiev that without using express-fileupload. eg:(formdata.append("fname":"pinto")) how can i retrieve the fname from the form data object without using express-fileupload?
if you are takking about inputs data check req.body
at front-end side i am sending form data content without adding any headers and trying to retrieve the response by convert it into res.json().But it is failed .what the issue here is?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.