Express.js application bug: Cannot read property 'transfer-encoding' of undefined - node.js

I am working on a blogging application (click the link to see the GitHub repo) with Express, EJS and MongoDB.
I am trying to introduce an add post image feature. Being quite new to Express, I am puzzled about the problem I have ran into.
The add post form:
<form action="/dashboard/post/add" method="POST" enctype="multipart/form-data" class="mb-0">
<div class="form-group">
<input type="text" class="form-control" name="title" value="<%= typeof form!='undefined' ? form.titleholder : '' %>" placeholder="Title" />
</div>
<div class="form-group">
<input type="text" class="form-control" name="excerpt" value="<%= typeof form!='undefined' ? form.excerptholder : '' %>" placeholder="Excerpt" />
</div>
<div class="form-group">
<textarea rows="5" class="form-control" name="body" placeholder="Full text"><%= typeof form!='undefined' ? form.bodyholder : '' %></textarea>
</div>
<label for="postimage">Upload an image</label>
<div class="form-group">
<input type="file" name="postimage" id="postimage" size="20">
</div>
<div class="form-group d-flex mb-0">
<div class="w-50 pr-1">
<input type="submit" value="Add Post" class="btn btn-block btn-md btn-success">
</div>
<div class="w-50 pl-1">
Cancel
</div>
</div>
</form>
In the controller my addPost() methos looks like this:
const Post = require('../../models/post');
const { validationResult } = require('express-validator');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/images')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + '.png')
}
});
const upload = multer({ storage: storage }).single('postimage');
exports.addPost = (req, res, next) => {
upload(function(err) {
if (err) {
console.log("There was an error uploading the image.");
}
res.json({
success: true,
message: 'Image uploaded!'
});
})
var form = {
titleholder: req.body.title,
excerptholder: req.body.excerpt,
bodyholder: req.body.body
};
const errors = validationResult(req);
const post = new Post();
post.title = req.body.title;
post.short_description = req.body.excerpt;
post.full_text = req.body.body;
if (!errors.isEmpty()) {
req.flash('danger', errors.array())
res.render('admin/addpost', {
layout: 'admin/layout',
website_name: 'MEAN Blog',
page_heading: 'Dashboard',
page_subheading: 'Add New Post',
form: form
});
} else {
post.save(function(err) {
if (err) {
console.log(err);
return;
} else {
req.flash('success', "The post was successfully added");
req.session.save(() => res.redirect('/dashboard'));
}
});
}
}
I alse have const multer = require("multer"); at the top (of the controller).
The "Add New Post" form worked fine until I tried to add this upload feature. The code I currently have throws this error:
Cannot read property 'transfer-encoding' of undefined
at hasbody (C:\Path\To\Application\node_modules\type-is\index.js:93:21)
What am I doing wrong?

You are missing req and res inside your upload(), try adding those two like
upload(req, res, function (err) {
if (err) {
console.log("There was an error uploading the image.");
}
res.json({
success: true,
message: 'Image uploaded!'
});
})

Related

cloudinary multiple file upload error nodejs

I am trying to do a multiple file upload using Cloudinary, but for some reason, it only picks the last file I upload and not all 4 of the files, it returns only one file in the array.
Here are the files
Multer.js
const path = require("path");
//setting the storage engine
const storage = multer.diskStorage({
filename: function (req, file, cb) {
cb(
null,
file.fieldname + "-" + Date.now() + path.extname(file.originalname)
);
},
});
// Check File Type
function checkFileType(file, cb) {
// Allowed extension format
const filetypes = /jpeg|jpg|png|pdf/;
// Check the extension format
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
// Check mime
const mimetype = filetypes.test(file.mimetype);
if (mimetype && extname) {
return cb(null, true);
} else {
req.flash("error", "Invalid File");
cb("ERROR: Please upload a valid filetype");
return res.redirect("back");
}
}
//initialize the file uplaod
const upload = multer({
storage: storage,
//limits file size
fileFilter: function (req, file, cb) {
checkFileType(file, cb);
},
});
module.exports = { upload };
cloudinary.js
const { CLOUDINARY_CLOUD_NAME, CLOUDINARY_API_KEY, CLOUDINARY_API_SECRET } =
process.env;
const cloudinarySetup = async () => {
cloudinary.config({
cloud_name: CLOUDINARY_CLOUD_NAME,
api_key: CLOUDINARY_API_KEY,
api_secret: CLOUDINARY_API_SECRET,
});
};
// cloudinary upload method
const cloudinaryMediaUpload = async (file, folder) => {
await cloudinarySetup();
return new Promise((resolve) => {
cloudinary.uploader.upload(
file,
{
resource_type: "auto",
folder: folder,
},
(err, result) => {
if (err) throw err;
resolve({
url: result.secure_url,
id: result.public_id,
});
}
);
});
};
module.exports = { cloudinaryMediaUpload };
defaultController.js
const { Business } = require("../models/business");
const { cloudinaryMediaUpload } = require(".././config/cloudinary");
module.exports = {
indexGet: (req, res) => {
let pageTitle = "Home";
res.render("default/index", { pageTitle });
},
aboutGet: (req, res) => {
let pageTitle = "About";
res.render("default/about", { pageTitle });
},
contactGet: (req, res) => {
let pageTitle = "Contact";
res.render("default/contact", { pageTitle });
},
registerGet: (req, res) => {
let pageTitle = "Register";
const { businessName, businessAddress, businessPhone } = req.body;
res.render("default/register", {
pageTitle,
businessName,
businessAddress,
businessPhone,
});
},
registerPost: async (req, res) => {
const { businessName, businessAddress, businessPhone, businessCategory } =
req.body;
// console.log(req.body);
console.log(req.files);
let errors = [];
// Checking Required Field
if (
!businessName ||
!businessAddress ||
!businessPhone ||
!businessCategory
) {
errors.push({ msg: "All fields are required" });
}
let validatePhone = validatePhoneNumberSync(businessPhone);
if (!validatePhone.isValid === true) {
errors.push({ msg: "Invalid phone number" });
}
if (errors.length > 0) {
let pageTitle = "Register";
res.render("default/register", {
pageTitle,
businessName,
businessAddress,
businessPhone,
errors,
});
} else {
Business.findOne({ businessName }).then(async (buss) => {
if (buss) {
errors.push({
msg: "A business with this name is already registered",
});
let pageTitle = "Register";
res.render("default/register", {
pageTitle,
businessName,
businessAddress,
businessPhone,
errors,
});
} else {
// uploading files to cloud
const uploader = async (path) => {
const folderName = businessName
.trim()
.toLowerCase()
.replace(/^[^A-Z0-9]+/gi, function (match) {
return arguments[2].toUpperCase();
});
console.log(folderName);
await cloudinaryMediaUpload(path, "folderName");
};
const urls = [];
const files = req.files;
for (const file of files) {
const { path } = file;
const cloudPath = await uploader(path);
urls.push(cloudPath);
}
const newBusiness = new Business({
businessName,
businessAddress,
businessPhone,
businessCategory,
});
newBusiness.save();
req.flash("success_msg", "Business successfully registered");
res.redirect("/");
}
});
}
},
};
register.ejs
<%- include("../partials/default/header") %>
<div class="form_wrapper">
<div class="form_container">
<div class="title_container">
<h2 style="color: #65b54a;">Business Registration</h2>
</div>
<div class="row clearfix">
<div class="">
<%- include ("../partials/messages"); %>
<form action="/register" enctype="multipart/form-data" method="POST">
<div class="row clearfix">
<div class="col_half">
<div class="input_field"> <span><i aria-hidden="true" class="fa fa-user"></i></span>
<input type="text" name="businessName" placeholder="Business Name" required
value="<%= businessName || '' %>" />
</div>
</div>
<div class="col_half">
<div class="input_field"> <span><i aria-hidden="true" class="fa fa-map-marker"></i></span>
<input type="text" name="businessAddress" placeholder="Business Address" required
value="<%= businessAddress || '' %>" />
</div>
</div>
</div>
<div class="row clearfix">
<div class="col_half">
<div class="input_field"> <span><i aria-hidden="true" class="fa fa-phone"></i></span>
<input type="text" name="businessPhone" placeholder="Business Phone Number" required
value="<%= businessPhone || '' %>" />
</div>
</div>
<div class="col_half">
<div class="input_field select_option">
<select name="businessCategory">
<option selected disabled>Business Category</option>
<option>Technology</option>
<option>Agriculture</option>
<option>Fashion</option>
<option>Entertainment</option>
</select>
<div class="select_arrow"></div>
</div>
</div>
</div>
<!-------------------------Files upload section---------------->
<div class="row clearfix">
<div class="col_half">
<div class="input_field d-flex justify-content-around">
<input type="file" name="bussFile" multiple accept=".pdf, .png, .jpg, .jpeg" id="img"
style="display:none;" />
<label for="img" class="btn btn-success"><span class="d-none d-md-inline mr-2"><i aria-hidden="true"
class="fas fa-upload"></i></span>Upload Incorporation Document</label>
</div>
</div>
<div class="col_half">
<div class="input_field d-flex justify-content-around">
<input type="file" name="bussFile" multiple accept=".pdf, .png, .jpg, .jpeg" id="img"
style="display:none;" />
<label for="img" class="btn btn-success"><span class="d-none d-md-inline mr-2"><i aria-hidden="true"
class="fas fa-upload"></i></span>Upload Company's Profile</label>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col_half">
<div class="input_field d-flex justify-content-around">
<input type="file" name="bussFile" multiple accept=".pdf, .png, .jpg, .jpeg" id="img"
style="display:none;" />
<label for="img" class="btn btn-success"><span class="d-none d-md-inline mr-2"><i aria-hidden="true"
class="fas fa-upload"></i></span>Upload Financial Statements</label>
</div>
</div>
<div class="col_half">
<div class="input_field d-flex justify-content-around">
<input type="file" name="bussFile" multiple accept=".pdf, .png, .jpg, .jpeg" id="img"
style="display:none;" />
<label for="img" class="btn btn-success"><span class="d-none d-md-inline mr-2"><i aria-hidden="true"
class="fas fa-upload"></i></span>Upload Investment Pitch Deck</label>
</div>
</div>
</div>
<input class="button" type="submit" value="Register" />
<!-- <button type="submit" class="btn btn-info">
Register
</button> -->
</form>
</div>
</div>
</div>
</div>
<%- include("../partials/default/footer") %>
And this happens to be the array I get back when I submit. Only the last file upload was picked and not all 4 of the uploads
[
{
fieldname: 'bussFile',
originalname: 'tab.png',
encoding: '7bit',
mimetype: 'image/png',
destination: 'C:\\Users\\HP\\AppData\\Local\\Temp',
filename: 'bussFile-1664784129792.png',
path: 'C:\\Users\\HP\\AppData\\Local\\Temp\\bussFile-1664784129792.png',
size: 68329
}
]
When I check out the documentation here -
It looks like only a single "file" is supported at one time.
https://cloudinary.com/documentation/image_upload_api_reference#upload_required_parameters
Details about how to upload more in parallel here:
https://support.cloudinary.com/hc/en-us/articles/202520662-How-can-I-bulk-upload-my-images-#:~:text=Cloudinary's%20upload%20API%20supports%20a,files%20in%20a%20short%20term.

req.file is undefined in multer image upload -- NodeJS, Angular

I am trying to upload an image for a blog posts using Multer. I am using mongodb and NodeJS for the backend and Angular for the front end. Whenever I perform the POST request and check in the console, the req.file is always undefined. I have tried using Multer's upload.any() with req.files and req.files[0].filename but to no avail. I have no clue why it stays undefined.
Here's my Multer Code:
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'public');
},
filename: (req, file, cb) => {
console.log(file);
var filetype = '';
if(file.mimetype === 'image/gif') {
filetype = 'gif';
}
if(file.mimetype === 'image/png') {
filetype = 'png';
}
if(file.mimetype === 'image/jpeg') {
filetype = 'jpg';
}
cb(null, 'file-' + Date.now() + '.' + filetype);
}
});
const upload = multer({storage: storage, limits: { fieldSize: 10 * 1024 * 1024 } });
Here's the Server POST request:
router.post('/newPost', passport.authenticate('jwt', { session: false}), upload.single('image'), function(req, res, next) {
console.log(req.file);
let newPost = new Post({
postTitle: req.body.postTitle,
postAuthor: req.body.postAuthor,
postImgUrl: 'http://localhost:3000/public/' + req.file.filename,
postContent: req.body.postContent
});
Post.create(newPost, (err, user) => {
if(err) {
res.json({success: false, msg: 'Post failed to submit'});
} else {
res.json({success: true, msg: 'Successfully Posted'});
}
});
});
This is my Angular Service for the POST request:
addPost(post): Observable<post> {
this.loadToken();
const head = this.headers.append("Authorization", this.authToken);
return this.http.post<post>(this.baseUri + "/newPost", post, { headers: head });
}
This is my TypeScript Component code:
export class BlogAddComponent implements OnInit {
postTitle: '';
postAuthor: '';
postContent: '';
postImgUrl: string;
post: any[] = [];
postForm: FormGroup;
public editor = Editor;
config;
constructor(private postService: PostService,
private formBuilder: FormBuilder,
private router: Router,
private flashMessage: FlashMessagesService) {
}
onFileSelect(event: Event) {
const file = (event.target as HTMLInputElement).files[0];
this.postForm.patchValue({ image: file });
const allowedMimeTypes = ["image/png", "image/jpeg", "image/jpg"];
if (file && allowedMimeTypes.includes(file.type)) {
const reader = new FileReader();
reader.onload = () => {
this.postImgUrl = reader.result as string;
};
reader.readAsDataURL(file);
}
}
ngOnInit(): void {
this.postForm = new FormGroup({
postTitle: new FormControl(null),
postAuthor: new FormControl(null),
postContent: new FormControl(null),
postImgUrl: new FormControl(null)
});
}
onBlogSubmit() {
this.postService.addPost(this.postForm.value).subscribe(
data => {
this.flashMessage.show('Blog Submitted Successfully', {cssClass: 'alert-success', timeout: 3000});
this.router.navigate(['/blog-page']);
},
error => {
this.flashMessage.show('Something Went Wrong', {cssClass: 'alert-danger', timeout: 3000});
}
);
}
}
And this is my Component HTML:
<body>
<div [formGroup]="postForm" class="container" *ngIf="post">
<h1 class="mb-4">New blog post</h1>
<form [formGroup]="postForm" (ngsubmit)="onBlogSubmit()" enctype="multipart/form-data">
<div class="form-group">
<label for="postImgUrl">Image</label>
<input (change)="onFileSelect($event)" type="file" class="form-control" name="image" required>
</div>
<div class="form-group">
<label for="title">Title</label>
<input formControlName="postTitle" type="text" class="form-control" placeholder="Title" name="postTitle" required>
</div>
<div class="form-group">
<label for="author">Author</label>
<input formControlName="postAuthor" type="text" class="form-control" placeholder="Author" name="postAuthor" required>
</div>
<br>
<div class="form-group">
<ckeditor formControlName="postContent" name="postContent" [editor]="editor" [config]="config"></ckeditor>
</div>
<br>
<div class="form-group">
<a routerLink="/blog-page" class="btn btn-warning">Cancel</a>
<button type="submit" class="btn btn-primary" (click)="onBlogSubmit()">Save</button>
</div>
</form>
</div>
</body>
I am really stuck with this. Any help, pointers or guidance are greatly appreiciated. Thank You very much.
You should send formData with the name image as you configured on backend:
addPost(post): Observable<post> {
this.loadToken();
const head = this.headers.append("Authorization", this.authToken);
const formData: FormData = new FormData();
formData.append('image', post.postImgUrl);
return this.http.post<post>(this.baseUri + "/newPost", formData, { headers: head });
}

File Fail To Upload

Started learning nodejs recently, and am currently trying to perform a task that involves file upload.. With the aid of multer documentation and Youtube video, was able to set up the module and middleware and file path etc. but for some reasons, the file don't upload. i can see the file object in my console, but my browser keeps loading.
Would love if someone can help point my errors to allow the file upload to specifies folder, and also give me a tip on how to trap errors not rendered on the error file Thank you. Below are my codes:
register.hbs
{{>header}}
<body>
<h1>Hello World</h1>
<h2>{{this.title}}</h2>
<div class="mb-3">
{{#each data}}
<div class="alert alert-danger">{{msg}}</div>
{{/each}}
</div>
<form action="" method="POST" enctype="multipart/form-data">
<label for="exampleInputEmail1" class="form-label">First Name</label>
<input type="text" class="form-control" name="fname" aria-describedby="emailHelp">
<div>
</div>
</div>
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">Last Name</label>
<input type="text" class="form-control" name="lname" aria-describedby="emailHelp">
</div>
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">Email address</label>
<input type="email" class="form-control" name="email" aria-describedby="emailHelp">
</div>
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">Password</label>
<input type="password" class="form-control" name="pwd">
</div>
<div class="mb-3">
<label for="exampleInputFile" class="form-label">Select Image</label>
<input type="file" class="form-control" name="image" id="image">
</div>
<div class="mb-3 form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1">
<label class="form-check-label" for="exampleCheck1">Check me out</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</body>
</html>
router file
var express = require('express');
var router = express.Router();
const {check,validationResult}= require('express-validator');
const multer=require('multer')
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/uploads')
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
cb(null, file.fieldname + '-' + uniqueSuffix)
}
})
var upload = multer({
storage: storage,
limits:{
fieldSize:1024*1024*100
} })
router.post('/register',upload.single('image'), [
check('fname')
.isLength({ min: 8 })
.withMessage('First name must be minimum of 8 characters')
.isAlpha()
.withMessage('first name must contain only alphabeth'),
check('lname').isLength({min:8}),
check('email').isEmail()
], (req, res,next)=>{
const errors = validationResult(req)
if (!errors.isEmpty()) {
//const data=errors.array();
console.log(errors)
res.render('users/register',{title:"Create Account", data:errors.array()});
//return res.status(422).json({errors: errors.array()})
}
console.log(req.file)
const fname = req.body.fname
const lname = req.body.lname
const email = req.body.email
console.log(req.errors)
// res.render('users/register');
})
Not really sure about your case, in my case I using multer like this:
I seperate multer to a file multerUploaderMiddleware.js
const multer = require("multer");
const path = require("path");
const util = require("util");
//Change this to diskStorage like your code above
//I use memory storage
const multerStorage = multer.memoryStorage()
function chapterIsExisted(req) {
// My custom error handling function
return (
Chapter
.findOne({ comicSlug: req.params.slug, chapter: `chapter-${req.body.chapter}` })
.then(chapterExisted => {
if (chapterExisted == null) { return false }
return true
}))
};
// This filter function for error handling
const filter = async (req, file, cb) => {
//as I remember if you want the file to success
// then return cb(null, true)
// else return cb(null, false)
if (req.check == 'nocheck') {
return cb(null, true)
} else {
var check = await chapterIsExisted(req)
if (check == false) {
cb(null, true)
} else {
let errorMess = `chapter ${req.body.chapter} existed`
return cb(errorMess, false);
}
}
};
const upload = multer({
storage: multerStorage,
fileFilter: filter
}).single("image", 200);
// Turn this middleware function into promise
let multipleUploadMiddleware = util.promisify(upload);
module.exports = multipleUploadMiddleware;
And In my route controller:
// get the exported function
const MulterUploadMiddleware =
require("../middlewares/MulterUploadMiddleWare");
class S3UploadController {
// [POST] / stored /comics /:slug /S3-multiple-upload
multipleUpload = async (req, res, next) => {
// The function you exported from middleware above
MulterUploadMiddleware(req, res)
.then(async () => {
//when the upload is done you get some data back here
Console.log(req.file)
// do stuff
})
.then(() => res.redirect('back'))
.catch(err => next(err))
})
}

ExpressJs File upload Issue

Even on uploading a file with .jpg or .png format it shows
format not allowed, please upload file with '.png','.gif','.jpg'.
I don't know why it is happening. How to solve or fix this issue? I tried to use ways suggested on some other websites to solve this issue but I wasn't able to fix this issue.
routes.js:
const {
con,
sessionStore
} = require('./config/db');
exports.new = function(req, res){
message = '';
if(req.method == "POST"){
const post = req.body;
const username= post.username;
const title= post.title;
const state= post.state;
const category= post.category;
const description= post.description;
if (!req.files)
return res.status(400).send('No files were uploaded.');
const file = req.files.uploaded_image;
var img_name=file.name;
if(file.mimetype == "image/jpeg" ||file.mimetype == "image/png"||file.mimetype == "image/gif" ){
file.mv('public/imgs/uploads/'+file.name, function(err) {
var sql = "INSERT INTO `nt_data`(`username`,`title`,`state`,`category`, `images` ,`description`) VALUES ?";
var query = con.query(sql, [username, title, state, category, img_name, description], function(err) {
if (!err) {
res.redirect('show/' + username);
}
else {
message = "This format is not allowed , please upload file with '.png','.gif','.jpg'";
res.render('new.ejs',{message: message});
}
});
});
}
}
else {
res.render('new');
}
};
exports.show = function(req, res){
let message = '';
var username = req.params.username;
const sql="SELECT * FROM `nt_data` WHERE `username`='"+username+"'";
con.query(sql, function(err, result){
if(result.length <= 0)
message = "show not found!";
res.render('show.ejs',{data:result, message: message});
});
};
part of my new.ejs file
<form action="/" method="POST" role="form" enctype="multipart/form-data" class="was-validated">
<% if (message.length > 0) { %>
<div class="alert alert-success col-sm-12"><%= message %></div>
<% } %>
<div class="input-group mb-3 input-group-lg">
<div class="input-group-prepend">
<span class="input-group-text">Username</span>
</div>
<input type="text" class="form-control" required placeholder="Enter Username" name="username">
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
<div class="input-group mb-3 input-group-lg">
<div class="input-group-prepend">
<span class="input-group-text">Title</span>
</div>
<input type="text" class="form-control" required placeholder="Enter Title" name="title">
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
<div class="custom-file mb-3">
<input type="file" class="custom-file-input" id="customFile" name="uploaded_image">
<label class="custom-file-label" for="uploaded_image">Choose file</label>
</div>
You should use multer for image or file uploading to server. Because you must use buffer to transfer data from user to local or public server and must create session. You can do these using multer easily.
You can check
https://www.npmjs.com/package/multer

cannot read property filename multer and node error

I have just started building this example of using multer with node js. I built a separate project which actually runs fine, but when I copied over the same setting making minor changes to routes on like from app.get to router.get, I am getting the error:
TypeError: Cannot read property 'filename' of undefined
here is my code for the route:
router.post('/userprofilepic', ensureAuthenticated, (req, res) => {
upload(req, res, (err) => {
if (err) {
res.render('/user/userdashboard', {
msg: err
});
} else {
const newImage = {
imageName: req.file.filename,
image_caption: req.body.image_caption,
member_id: req.user.member_id
}
new Image(newImage)
.save()
.then(image => {
req.flash('success_msg', 'Image added');
res.redirect('/user/userdashboard');
})
.then(resize => {
let imgHeight = 150;
let imgWidth = 150;
sharp(req.file.path)
.blur(.3)
.toFile('public/thumbs/blurred_' + req.file.originalname, function (err) {
if (!err) {
req.flash('success_msg', 'Thumbnail created');
//res.redirect('/');
}
});
})
.catch(error => {
console.log(error);
});
}
});
});
This is my multer configuration:
// Set storage engine
const storage = multer.diskStorage({
destination: './public/uploads/',
filename: function (req, file, cb) {
cb(null, req.user.member_id + '_' + Date.now() + '_' + file.originalname);
}
});
// Init upload
const upload = multer({
storage: storage
}).single('imageName');
//load user model
require('../models/User');
const User = mongoose.model('users');
//load user profile model
require('../models/Profile');
const Profile = mongoose.model('profiles');
// Load images model
require('../models/Images');
const Image = mongoose.model('images');
and finally my form:
<form action="/user/userprofilepic" method="POST" enctype="multipart/form-data">
<div class="form-group">
<img id="blah" src="#" alt="your image" height="300" />
</div>
<div class="form-group">
<label for="exampleFormControlFile1">Example file input</label>
<input type="file" class="form-control-file" name="imageName" id="imageName">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Image Caption</label>
<input type="text" class="form-control" name="image_caption">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<input type="text" class="form-control" name="member_id" value="{{user.member_id}}" hidden>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
I tried console.log(req.file) and it's undefined. For the life of me I am unable to understand what I did wrong.
Please advise.
Figured it out...it was my mistake, in my server. js I had initialized an upload method which was overriding the multer upload function and hence no filename.

Resources