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.
Related
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 });
}
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))
})
}
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!'
});
})
I have different form inputs to upload in a single page on how to upload using multer?
app.js :
const multer = require('multer');
const fileStroge = multer.diskStorage({
destination: (req, file,cb)=>{
cb(null, 'upload');
},
filename: (req, file, cb) =>{
cb(null, file.originalname);
}
});
const fileFilter = (req, file, cb)=>{
if(file.mimetype == 'application/octet-stream'){
cb(null,true);
}else{
cb(null,false);
}
};
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extented: true}));
app.use(multer({ storage: fileStroge, fileFilter: fileFilter}).single('filename'));
// app.use(multer({ storage: fileStroge, fileFilter: fileFilter}).single('filenameS'));
below is my js file
user.js:
exports.uploadedData = (req, res)=>{
const file = req.file;
// console.log(file);
if( file == undefined){
res.send("you can upload excel sheet only");
}
readXlsxFile(req.file.path).then((rows) =>{
var database = mysql.createConnection(
{ host: 'localhost', user: 'root', password: 'ilensys#123', database: 'harness_db'}
);
var query = database.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT IGNORE INTO harnes_detials (id, item_des, harness_drw_pin, harness_type, harness_conn_type, mating_crimp, design_volt, connectors_mating_mfg, mating_connector_part_no, design_current, gauge, connector_type, connect_gender, no_pins, no_rows, connectors, manufacture, contact_rating, voltage_rating, maximum_temp, connector_orientation, d_connector_type, d_connector_gender, d_mating_connector_part_no, d_connector_mating, d_connectors_mating_mfg, d_no_pins, d_no_rows,d_connector, d_manufacture, d_contact_rating, d_voltage_rating, d_maximum_temp, d_connector_orientation, d_guage, d_mating_crimp, createdAt, updatedAt) VALUES ? ";
var newSql = "LOAD DATA INFILE 'req.file.path' INTO TABLE harnes_detials";
var values = rows.slice(1);
// console.log(values);
database.query(sql, [values], function (err, result) {
// console.log(result);
if(err){
console.log(err);
}else{
res.render("success");
console.log( "row inserted: "+ result.affectedRows);
}
});
});
});
};
exports.uploadedSourceData = (req, res)=>{
const file = req.file;
// console.log(file);
if( file == undefined){
res.send("you can upload excel sheet only");
}
readXlsxFile(req.file.path).then((rows) =>{
var database = mysql.createConnection(
{ host: 'localhost', user: 'root', password: 'ilensys#123', database: 'harness_db'}
);
var query = database.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT IGNORE INTO matingsources (id, mating_source_connectors,connector_type, source_connectors, gauge) VALUES ? ";
var newSql = "LOAD DATA INFILE 'req.file.path' INTO TABLE matingsources";
var values = rows.slice(1);
console.log(values);
database.query(sql, [values], function (err, result) {
console.log(result);
if(err){
console.log(err);
}else{
res.render("success");
console.log( "row inserted: "+ result.affectedRows);
}
});
});
});
};
below is my ejs file with inputs :
<form class="needs-validation" action="/uploadData" method="post" enctype="multipart/form-data" novalidate>
<div class="custom-file mb-3">
<input type="file" class="custom-select custom-file-input" id="filename" name="filename" required>
<label class="custom-file-label" for="customFile">Choose file</label>
<div class="valid-feedback">Looks Good!</div>
<div class="invalid-feedback">need to upload a file!</div>
</div>
<div class="mt-3 text-center">
<button type="submit" class="btn btn-primary">Upload</button>
<a class="btn btn-secondary" href="javascript:history.back()" role="button">Cancel</a>
</form>
<form class="needs-validation" action="/uploadSourceData" method="post" enctype="multipart/form-data" novalidate>
<div class="custom-file mb-3">
<input type="file" class="custom-select custom-file-input" id="filenameS" name="filenameS" required>
<label class="custom-file-label" for="customFile">Choose file</label>
<div class="valid-feedback">Looks Good!</div>
<div class="invalid-feedback">need to upload a file!</div>
</div>
<div class="mt-3 text-center">
<button type="submit" class="btn btn-primary">Upload</button>
<a class="btn btn-secondary" href="javascript:history.back()" role="button">Cancel</a>
</form>
its works fine with the first input upload option but with I upload from second input from other input its says :
multererror: unexpected field
but when I comment alternatively its works for both:
app.use(multer({ storage: fileStroge, fileFilter: fileFilter}).single('filename'));
// app.use(multer({ storage: fileStroge, fileFilter: fileFilter}).single('filenameS'));
but how to work with two different inputs uploads on the same page?? please help ??
Change the name attribute of the second input element to:
<input type="file" class="custom-select custom-file-input" id="filenameS" name="filename" required>
so that both input's have the same name attribute and then just use the multer route with 'filename'
i made a mean stack crud board and it works well. (angular2+, node.js, express, mongoDB)
after i tried to add upload function and it doesn' work.
this is error message.
compiler.js:486 Uncaught Error: Template parse errors:
Can't bind to 'uploader' since it isn't a known property of 'input'. (" <label for="file">파일</label>
<input type="file" name="single" ng2FileSelect [ERROR ->][uploader]="uploader" >
<button type="button" (click)="uploader.uploadAll()">
"): ng:///BoardModule/BoardCreateComponent.html#22:57
I've done making upload function by jsp but it's way more complicated.
do you have any idea of making upload function?
i would like to create a post with title, author, file 3 inputs
i uploaded my code github as well.
this is full code in github.
https://github.com/9aram/code-test
board-create.component.ts
import { Component } from '#angular/core';
import { Router } from '#angular/router';
import { BoardService } from '../../services/board.service';
import { Board } from '../../models/Board';
import {FileUploader} from 'ng2-file-upload';
#Component({
selector: 'app-board-create',
templateUrl: './board-create.component.html',
styles: []
})
export class BoardCreateComponent {
//파일 업로드 요청url
uploader:FileUploader = new FileUploader({
url:'http://localhost:3000/board-create'
});
fileInfo = {
originalname:'',
filename:''
};
board: any = {};
constructor(private router: Router, private boardService: BoardService) {
//업로드 요청 결과 받아오는 메소드
this.uploader.onCompleteItem = (item, response, status, header) =>{
this.fileInfo=JSON.parse(response);
};
}
saveBoard(boardForm) {
boardForm.form.value.originalname= this.fileInfo.originalname;
boardForm.for.value.filename=this.fileInfo.filename;
this.boardService.insertBoard(this.board)
.subscribe((res: Board) => { this.router.navigate(['/boards']); }, (err) => console.log(err));
}
}
board-create.component.html
<form #boardForm="ngForm" (ngSubmit)="saveBoard(boardForm)">
<div class="field">
<div class="control">
<label for="title">Title</label>
<input required name="title" id="title" [(ngModel)]="board.title" type="text" class="input">
</div>
</div>
<div class="field">
<div class="control">
<label for="author">Author</label>
<input required name="author" id="author" [(ngModel)]="board.author" type="text" class="input">
</div>
</div>
<div class="field">
<div class="control">
<label for="file">파일</label>
<input type="file" name="single" ng2FileSelect [uploader]="uploader" >
<button type="button" (click)="uploader.uploadAll()">
<<span>uploadd..</span>
</button>
</div>
</div>
<div class="field">
<div class="control">
<button class="button is-warning" routerLink="/boards"><i class="fas fa-arrow-left"></i>Back</button>
<button class="button is-link" type="submit" [disabled]="!boardForm.valid">Create</button>
</div>
</div>
</form>
node > api.js
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Board = require('../models/Board.js');
const bodyParser = require('body-parser');
const cors = require('cors');
const upload=require('../util/upload');
// API ROOT ROUTE
router.get('/', (req, res) => {
res.status(200).json({ status: 200, result: 'success' });
});
router.post('/', (req, res) => {
let newBoard = new Board({
title : request.body.title
}),
newBoard.save();
response.type("application/json");
response.send({
result:true
});
});
// GET ALL BoardS
router.get('/board', (req, res, next) => {
Board.find((err, products) => (err) ? next(err) : res.json(products));
});
// GET A Board
router.get('/board/:id', (req, res, next) => {
Board.findById(req.params.id, (err, post) => (err) ? next(err) : res.json(post));
});
// SAVE A Board
router.post('/board', upload.single('file'), (req, res, next) => {
response.type("application/json");
response.send({result:true,
originalname: request.file.originalname,
filename: request.file.filename()});
Board.create(req.body, (err, post) => (err) ? next(err) : res.json(post));
});
module.exports = router;
upload.js
const multer = require('multer');
const storage = multer.diskStorage({
description:function(request, file, cb){
cb(null, __dirname + '/../upload');
}
filename: function(request, file, cb){
let datetimestamp=Date.now();
let originalFileName=file.originalname;
originalFileName=originalFileName.split('.');
let originalName=originalFileName[originalFileName.length - 1];
cb(null, file.filename + '-' + datetimestamp+ '.'+originalName);
}
});
//starage 객체만들어 multer의 멤버 설정
const upload = multer({
storage: storage
})
//외부에서 upload객체 사용할 수 있또록 함
module.exports = upload;
Could you please try to implement the same by checking the below code.
ust call uploadFile(url, file).subscribe() to trigger an upload
import { Injectable } from '#angular/core';
import {HttpClient, HttpParams, HttpRequest, HttpEvent} from '#angular/common/http';
import {Observable} from "rxjs";
#Injectable()
export class UploadService {
constructor(private http: HttpClient) { }
// file from event.target.files[0]
uploadFile(url: string, file: File): Observable<HttpEvent<any>> {
let formData = new FormData();
formData.append('upload', file);
let params = new HttpParams();
const options = {
params: params,
reportProgress: true,
};
const req = new HttpRequest('POST', url, formData, options);
return this.http.request(req);
}
}
You can get further information via below link.
https://appdividend.com/2018/05/25/angular-6-file-upload-tutorial/