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.
fileuploadmodule conflict withmulter?