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

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 });
}

Related

Multer not able to get the filename

I'm not able to get the filename or path from Multer. This is what I've done so far:
uploadcsv.js
const fileUpload = multer({
limits: 500000,
storage:multer.diskStorage({
destination: (req, file, cb) =>{
cb(null,'upload/csv')
},
filename: (req, file, cb) =>{
const ext = MIME_TYPE_MAP[file.mimetype]
cb(null, uuid + '.' + ext)
},
fileFilter: (req, file, cb) =>{
const isValid = !!MIME_TYPE_MAP[file.mimetype]
let error = isValid ? null : new Error('Invalid mime type')
cb(error, isValid)
}
})
})
Then the route api:
router.post('/contact/importcontact', JWTAuthenticationToken, fileUpload.single('csv'), async (req, res) => {
console.log(req.body)
console.log(req.file.filename)
const csvFilePath = req.file.filename
const stream = fs.createReadStream(csvfile);
const account= await Account.findOne({ acctid: { "$eq": req.body.acctid } })
try {
if (req.file == undefined)
return res.status(400).send({ msg: 'No files were uploaded.' });
csvtojson()
.fromFile(csvFilePath)
.then((jsonObj) => {
console.log(jsonObj);
})
// Async / await usage
const jsonArray = await csvtojson().fromFile(csvFilePath);
res.json({ success: "Uploaded Successfully", status: 200 })
} catch (error) {
res.json({ message: error })
}
})
Lastly, the react importcustomer.js
const handleCSVChange = (e) => {
console.log(e.target.files[0])
setCsvData(e.target.files[0])
setUploadButtonData(e.target.files[0].name)
}
const uploadCSVData = async (e) => {
setLoading(true)
const formData = new FormData();
formData.append("csv", csvData);
console.log(formData)
e.preventDefault()
const response = await Axios.post(process.env.REACT_APP_FETCH_URL + '/api/contact/importcontact', { formData: formData, acctid: lsData.acctid}, { withCredentials: true })
if (response.data.statusCode === "409") {
setMessage(response.data.msg)
setLoading(false)
}
else if (response.data.statusCode === "200") {
setLoading(false)
//history.push('/sources')
}
}
return (
<div className="col-12 grid-margin stretch-card">
<div className="card">
<div className="card-body">
<h4 className="card-title">Import Customer Data From CSV</h4>
<form className="forms-sample" enctype="multipart/form-data">
<div className="form-group">
<label for="files" className="btn btn-primary">{uploadButtonData}
<input id="files" type="file" name="csv" className="form-control" hidden accept="*.csv" onChange={handleCSVChange} /></label>
</div>
<button className="btn btn-primary" onClick={uploadCSVData} style={{ float: "right", width: "7rem" }} type="button">
{loading && <i className="fa fa-refresh fa-spin"></i>}
Upload CSV</button>
<div className="mt-3" style={{ textAlign: "center" }}>
<span id="msg" style={{ color: "red" }}>{message}</span>
</div>
</form>
</div>
</div>
</div>
)
Though I'm able to console.log(req.body) and console.log(e.target.files[0]) and getting the acctid and filename but returned empty for the console.log(formData) and console.log(req.file.filename) returned undefined. What have I missed? Many thanks in advance and greatly appreciate any helps. Thanks again
I have managed to solves this by appending the acctid to formData:
const formData = new FormData();
formData.append("csv", csvData);
formData.append("accctid", lsData.acctid);
const response = await Axios.post(process.env.REACT_APP_FETCH_URL + '/api/contact/importcontact', formData, { withCredentials: true })

Angular2+ : what is the simplest way to implement a simple file upload? my code is terribly not working

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/

Upload image and Json from Angular to Multer/Express

I would like to upload an image and a json to a server using Express and Multer.
When I test with Postman there is no problem but when I test with the Front-end in Angular, it seems that the image isn't sent.
Here are the codes :
problem-form.component.html
<div class="problemContainer">
<div class="problemForm">
<h2>Soumission de problème</h2>
<form [formGroup]="form" (ngSubmit)="submitForm()">
<p>
<mat-form-field class="inputFW">
<input matInput formControlName="User" placeholder="Adresse email">
<mat-error>This field is required</mat-error>
</mat-form-field>
</p>
<p>
<mat-form-field class="inputFW">
<input matInput value="{{machineName}}" placeholder="Nom de la machine" disabled>
<mat-error>Le nom de la machine est requis</mat-error>
</mat-form-field>
</p>
<p>
<mat-form-field class="inputFW">
<textarea matInput placeholder="Description du problème (max 200 caractères)" formControlName="Description" rows="3"></textarea>
</mat-form-field>
</p>
<p>
<label>Image (Optionnel)</label><br><br>
<input type="file" (change)="fileChange($event)" name="image" />
</p>
<button mat-raised-button color="primary">Envoyer</button>
</form>
</div>
function in the component that call the service
submitForm(){
if(this.form.valid){
let obj = this.form.value
obj.image = this.image
this.service.createProblem(obj).subscribe(data => console.log(data), err => {console.log(err)})
}else{
console.log("erreur")
}
}
function in the service that post to the server
createProblem(problem: Object){
console.log('roman')
let form = new FormData()
form.append('Name', problem['Name'])
form.append('Description', problem['Description'])
form.append('User', problem['User'])
form.append('image', problem['image'])
console.log(problem['image'])
return this.http.post(getUrl()+ `problems`, form);
}
Configuration of multer
let storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'images')
},
filename: function (req, file, cb) {
cb(null, 'problem_' + Date.now()+'.'+mime.extension(file.mimetype))
}
})
let upload = multer({ storage: storage });
The route that call a function in the controller
router.route('/')
/** GET /api/problems - Get list of Problems */
.get(pbCtrl.list)
/** POST /api/problem - create a new problem */
.post(/*validate(paramValidation.problem), */upload.single('image'), pbCtrl.create);
The function in the controller
function create(req, res, next) {
let photo
if(req.file != null)
photo = req.file.filename
PC.findOne({ Name: req.body.Name, Active: true }, { '_id': 0 }).exec()
.then((pc) => {
if (pc == null)
return res.sendStatus(400)
const newPc = new PC({
Name: pc.Name,
Local: pc.Local,
IP: pc.IP,
MAC: pc.MAC,
Comment: pc.Comment,
Active: pc.Active,
Problem: { User: req.body.User, Description: req.body.Description, Image: photo }
})
newPc.save()
.then(savedPC => {
res.json(savedPC);
//return next();
}).catch(e => { next(e); });;
})
.catch((err) => {
console.log(err)
res.sendStatus(400)
})
}
Thanks all
Resolved
function to load file
fileChange($event) {
let reader = new FileReader();
if($event.target.files && $event.target.files.length > 0) {
let file = $event.target.files[0];
this.file = file
}
}
function that submit the form
submitForm(){
if(this.form.valid){
let obj = this.form.value
obj.image = this.file
this.service.createProblem(obj).subscribe(data => this.openSnackBar('Votre demande a bien été enregistrée'), err => {console.log(err)})
}else{
console.log("erreur")
}
}
function in the service to post
createProblem(problem: Object){
let form = new FormData()
form.append('Name', problem['Name'])
form.append('Description', problem['Description'])
form.append('User', problem['User'])
form.append('image', problem['image'])
return this.http.post(getUrl()+ `problems`, form).map((res) => {
return res.json()
});
}

file upload in react and node js not working

i am trying very hard to upload file but no way i could find a clear solution .
i have tried many ways but not working . Now the console shows me 200 and give me message that file is uploaded but file is not going in the folder . i ahve checked file size limit and folder is ok but dont know why its not working. could any help please.
///react component
import { saveBasicUser, getOneBasicUser, uploadFile } from
'../../actions/basicAction';
this.state = { file: []};
handleChange(event) {
this.setState({
[event.target.name]: event.target.value,
file:
event.target.files})
}
handleSubmit(event) {
event.preventDefault();
var file = this.state.file
let formData = new FormData();
formData.append('file', file);
// console.log(obj);
console.log(formData);
// this.props.dispatch(saveBasicUser(obj ))
this.props.dispatch(uploadFile(formData ))
}
<form onSubmit={this.handleSubmit} encType="multipart/form-data">
<input type="file" name = "file" onChange={this.handleChange} />
<button type="submit" className="btn btn-success btn-lg">Submit</button>
////////action part
export function uploadFile(formData) {
console.log(formData)
return (dispatch) => {
return axios.post('/upload_file', {
headers: { 'content-type': 'multipart/form-data' },
data: formData
}).then(function (res) {
console.log(res)
}).catch(function (err) {
console.log(" err")
console.log(err)
})
}
}
//////server part
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now()+ path.extname(file.originalname))
}
})
var upload = multer({ storage: storage, limits: {fileSize : 1000000} }).single('file');
app.post('/upload_file', function(req, res){
upload(req, res, function(err) {
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
});
I have found the solution at last.
react JS
import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import Messages from '../Messages';
import classnames from 'classnames';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
import { getOneBasicUser ,uploadFile} from '../../actions/basicAction';
//--------------------------------------------------------------------------
class Upload extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};
this.handleChange = this.handleChange.bind(this);
this.handleFile = this.handleFile.bind(this);
}
//--------------------------------------------------------------------
//--------------------------------------------------------------------------
handleChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}
//--------------------------------------------------------------------------
handleFile(e) {
e.preventDefault();
var id = this.props.params.id;
console.log(id);
var formData = new FormData($('form')[0]);
var isFileExist = !!$('input[type=file]')[0].files[0];
if (isFileExist) {
$.ajax({
url: '/upload_file/'+ id,
type: 'POST',
data: formData,
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (e) {
if (e.lengthComputable) {
$('progress').attr({value: e.loaded, max: e.total});
$('#status').empty().text(parseInt((e.loaded / e.total * 100)) + '%');
}
}, false);
return xhr;
}.bind(this),
success: function (data) {
this.setState({
data: data
});
$('#status').empty().text('File Uploaded!');
}.bind(this),
error: function (xhr, status, err) {
console.log( err);
}.bind(this),
cache: false,
contentType: false,
processData: false
});
} else {
$('#status').empty().text('Please choose the file.');
}
}
//--------------------------------------------------------------------------
render() {
return (
<div className="container ca-container">
<div className="row">
<div className="col-md-12">
<h2> Upload File </h2>
<hr />
</div>
</div>
<form onSubmit={this.handleFile} encType="multipart/form-data">
<div className="row">
<div className="col-md-12">
<div className="col-md-6">
<h3 id="status" className ="label label-success"></h3>
<div className="form-group">
<label>
Name:
</label>
<input type="file" className="form-control" name="BasicUserFile" onChange={this.handleChange} placeholder="file" />
</div>
<div className="btn-group" role="group">
<button type="submit" value="Upload File" className="btn btn-success btn-lg">Upload</button>
</div>
</div>
</div>
</div>
</form>
</div>
);
}
}
// ======================== REDUX CONNECTORS ========================
const mapStateToProps = (state) => {
return {
//basicUser: state.basicUser.basicUser
};
};
export default connect(mapStateToProps)(Upload);
////server.js
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './uploads')
},
filename: function (req, file, cb) {
var basic_id = req.params.id
cb(null, file.fieldname + '-' + basic_id+ path.extname(file.originalname))
}
})
var upload = multer({ storage: storage, limits: {fileSize : 1000000} }).single('BasicUserFile');
app.post('/upload_file/:id', function(req, res){
console.log("000000000000000000000000000000000000000000000000")
console.log(req.params)
console.log("000000000000000000000000000000000000000000000000")
upload(req, res, function(err) {
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
});

file not uploading in react js and nodejs using multer

console.log giving this but file is not uploading
{
name:"sds",
shop_name:"dfgdfg",
address:"hfgdhf",
phone:"dfgfgd",
file:"C:\fakepath\favicon.png",
…
}account_status:"pending"address:"hfgdhf"backup_database:""expiry:"2017-10-19"file:"C:\fakepath\favicon.png"name:"sds"phone:"dfgfgd"shop_name:"dfgdfg"__proto__:{
data:"File is uploaded",
status:200,
statusText:"OK",
headers:{
…
},
config:{
…
},
…
}
component.js
import { saveBasicUser, getOneBasicUser, uploadFile } from '../../actions/basicAction';
class BasicUser extends React.Component {
constructor(props) {
super(props);
this.state = { name: '', phone: '', account_status: '', address: '', shop_name: '', file: [], backup_database: '', expiry: '' };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
//--------------------------------------------------------------------------
handleChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}
//--------------------------------------------------------------------------
handleSubmit(event) {
event.preventDefault();
var userId = this.props.params.id;
var obj = {};
obj["name"] = this.state.name
obj["shop_name"] = this.state.shop_name
obj["address"] = this.state.address
obj["phone"] = this.state.phone
obj["file"] = this.state.file
obj["backup_database"] = this.state.backup_database
obj["expiry"] = this.state.expiry
obj["account_status"] = this.state.account_status
console.log(obj)
this.props.dispatch(saveBasicUser(obj))
}
<form onSubmit={this.handleSubmit} encType="multipart/form-data">
<div className="row">
<div className="col-md-12">
<div className="form-group">
<label>
Name:
</label>
<input type="text" className="form-control" name="name" value={this.state.name} onChange={this.handleChange} placeholder="Zahid Hasan" /> .......................................
..........................................
</div>
<div className="form-group">
<label>File Upload</label>
<div className="form-group">
<label>File Upload</label>
<input type="file" className="form-control" name="file"value={this.state.file}b onChange={this.handleChange} />
</div>
</div>
<div className="btn-group" role="group">
<button type="submit" className="btn btn-success btn-lg">Submit</button>
</div>
action.js
export function saveBasicUser(obj) {
console.log(obj)
return (dispatch) => {
return axios.post('/basic-user/saveUser', {
headers: { 'content-type': 'multipart/form-data' },
obj: obj
}).then(function (res) {
browserHistory.push('/basic-dashboard');
console.log(res)
}).catch(function (err) {
console.log(" err")
console.log(err)
})
}
}
server.js
var multer = require('multer')
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './public/uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now()+ path.extname(file.originalname))
}
})
var upload = multer({ storage: storage, limits: {fileSize : 1000000} }).single('file')
app.post('/basic-user/saveUser',function(req,res){
upload(req, res, function(err) {
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
});
only way to upload file via ajax is use FormData try this.
handleSubmit(event) {
event.preventDefault();
var userId = this.props.params.id;
let formData = new FormData();
formData.append('name', this.state.name);
...
formData.append('file', this.state.file);
...
this.props.dispatch(saveBasicUser(obj))
}
And action file
export function saveBasicUser(obj) {
return (dispatch) => {
return axios.post('/basic-user/saveUser', obj).then(function (res) {
browserHistory.push('/basic-dashboard');
console.log(res)
}).catch(function (err) {
console.log(" err")
console.log(err)
})
}
}
I think you have not created proper destination to upload your image file at server side.
Please check your destination is exist /public/uploads in your server working dir.
Following links will help you on file upload functionality ,
Uploading files with React.js and Node.js
Sample Demo Code
Hopes this will help you !

Resources