this is my controller file from which im trying to upload an image to the mongoDB
const bodyParser=require('body-parser');
const mongoose = require('mongoose');
const Resource = mongoose.model('Resource');
const upload = require('express-fileupload');
const path=require('path');
app.use(upload())
app.post('/fileupload',function(req,res){
var resource = new Resource();
console.log(req.files);
var file=req.files.file;
var filename=file.name;
resource.name=filename;
file.mv('./resourceFiles/'+filename);
var fpath='./resourceFiles/'+filename;
resource.filePath=fpath;
resource.save((err)=>{
if(!err){
console.log("file record")
res.redirect('ownerHome');
}
else{
console.log("error during insertion:"+ err);
}
});
})
It throws an error:
TypeError: Cannot read property 'file' of null at /Users/Nikhil/Documents/node/auction/Controllers/owner.js:73:28 at Layer.handle [as handle_request] (/Users/Nikhil/Documents/node/auction/node_modules/express/lib/router/layer.js:95:5) at next (/Users/Nikhil/Documents/node/auction/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/Users/Nikhil/Documents/node/auction/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/Users/Nikhil/Documents/node/auction/node_modules/express/lib/router/layer.js:95:5) at /Users/Nikhil/Documents/node/auction/node_modules/express/lib/router/index.js:281:22 at Function.process_params (/Users/Nikhil/Documents/node/auction/node_modules/express/lib/router/index.js:335:12) at next (/Users/Nikhil/Documents/node/auction/node_modules/express/lib/router/index.js:275:10) at Busboy. (/Users/Nikhil/Documents/node/auction/node_modules/express-fileupload/lib/processMultipart.js:130:41) at Busboy.emit (events.js:323:22) at Busboy.emit (/Users/Nikhil/Documents/node/auction/node_modules/busboy/lib/main.js:37:33) at /Users/Nikhil/Documents/node/auction/node_modules/busboy/lib/types/multipart.js:304:17 at processTicksAndRejections (internal/process/task_queues.js:79:11)
Following is my fileupload.ejs file:
<form method="POST" enctype="multipart/form-data">
<br>Select file:<input type="file" name="file">
<br><input type="submit" value="Upload">
</form>
file
so you would need to access it viareq.files.file
, notreq.files.filetoupload
. There might be other issues but you might want to start there. – Jason Roman