looking to upload multiple images with express-fileupload - node.js

looking to upload multiple images i am able to do it individually as in code but now i want all gallery images to be sent in a single input and support multiple uploads without restricting numbers here is my code.
router.post('/add-product', isAdmin, function (req, res, next) {
console.log(req.files);
errorMsg = req.flash('error')[0];
successMsg = req.flash('success')[0];
var imageFile, imageFile1, imageFile2, imageFile3;
if (!req.files) {
res.send('No files were uploaded.');
return;
}
imageFile = req.files.imageFile;
imageFile1 = req.files.imageFile1;
imageFile2 = req.files.imageFile2;
imageFile3 = req.files.imageFile3;
imageFile.mv('public/images/' + req.user._id + req.body.code + req.body.name + '.png', function (err) {
if (err) {
res.status(500).send(err);
}
});
imageFile1.mv('public/images/' + req.user._id + req.body.code + req.body.name + 'g1' + '.png', function (err) {
if (err) {
res.status(500).send(err);
}
});
imageFile2.mv('public/images/' + req.user._id + req.body.code + req.body.name + 'g2' + '.png', function (err) {
if (err) {
res.status(500).send(err);
}
});
imageFile3.mv('public/images/' + req.user._id + req.body.code + req.body.name + 'g3' + '.png', function (err) {
if (err) {
res.status(500).send(err);
}
});
product = new Product({
name: req.body.name,
code: req.body.code,
Wifi: req.body.Wifi,
campfire: req.body.campfire,
Pool: req.body.Pool,
parking: req.body.parking,
title: req.body.title,
Duration: req.body.Duration,
Product_Group: req.body.Product_Group,
price: parseFloat((req.body.price * 100).toFixed(2)),
description: req.body.description,
shippable: req.body.shippable,
taxable: req.body.taxable,
category: req.body.category,
Longitude: req.body.Longitude,
Latitude: req.body.Latitude,
imagePath: '/images/' + req.user._id + req.body.code + req.body.name + '.png',
imagePathg1: '/images/' + req.user._id + req.body.code + req.body.name + 'g1' + '.png',
imagePathg2: '/images/' + req.user._id + req.body.code + req.body.name + 'g2' + '.png',
imagePathg3: '/images/' + req.user._id + req.body.code + req.body.name + 'g3' + '.png',
});
console.log(product);
product.save(function (err) {
if (err) {
req.flash('error', 'Error: ' + err.message);
return res.redirect('/admin/products');
}
//console.log("product: " + product);
return res.redirect('/admin/products');
});
});
the front part is as in the below code html part of the same with different inputs for different images but now looking to make multiple inputs for the same the node module supporting the function is express-fileupload
<div class="form-group">
<ul class="list-group">
<li class="list-group-item">
<label for='imageFile'>Display Image</label>
<input type='file' name='imageFile' class='form-control'>
</li>
</ul>
</div>
<div class="form-group">
<ul class="list-group">
<li class="list-group-item">
<label for='imageFile1'>Gallery1</label>
<input type='file' name='imageFile1' class='form-control'>
</li>
</ul>
</div>
<div class="form-group">
<ul class="list-group">
<li class="list-group-item">
<label for='imageFile2'>Gallery2</label>
<input type='file' name='imageFile2' class='form-control'>
</li>
</ul>
</div>
<div class="form-group">
<ul class="list-group">
<li class="list-group-item">
<label for='imageFile3'>Gallery3</label>
<input type='file' name='imageFile3' class='form-control'>
</li>
</ul>
</div>

You can do something like this
if(req.files){
const file = req.files.filename;
for(let i = 0 ; i < file.length; i++){
file[i].mv('./upload/'+file[i].name, function (err){
if(err){
res.send(err);
}
})
}
res.send('files uploaded);
}
Make sure to change the upload directory to ur directory

Using express-fileupload, I uploaded multiple and single images
if (!req.files) {
next()
}
else {
//for uploading mutiple images
var uploadedFiles = []
// images is a field name
uploadedData = req.files.images
if(uploadedData.length > 1){
for (let i = 0; i < uploadedData.length; i++) {
const uploadPath = path.join(__dirname, '..', '/uploads/',
uploadedData[i].name)
const fileName = path.join(__dirname, '..', '/uploads/',
uploadedData[i].name)
uploadedFiles.push(fileName)
res.filepath = uploadedFiles
uploadedData[i].mv(uploadPath, function (err) {
if (err) {
res.send(err);
}
})
}
}
else{
// for single image
const uploadPath = path.join(__dirname, '..', '/uploads/', uploadedData.name)
const fileName = path.join(__dirname, '..', '/uploads/', uploadedData.name)
uploadedFiles.push(fileName)
res.filepath = uploadedFiles
uploadedData.mv(uploadPath, function (err) {
if (err) {
res.send(err);
}
})
}
next()
}
}

In this code I am trying to save a file in the ./uploads folder and entering the details into a database as i move each file, also i am changing the file name as they get moved to the uploads folder with a unique name. I used a library called uniqueFilename for this you can omit the uniqueFilename and database operations as per your need. Also var ext is used to store the extension of that file and used later to add in the database..
You can also call savemulti to save a single file.
const savemulti = async (file)=>{
var filename = file.name
var re = /(?:\.([^.]+))?$/;
var ext = re.exec(filename)[1];
var nm = uniqueFilename('')
file.mv('./uploads/'+nm+'.'+ext,(err)=>{
if(err){
throw err
}else{
var sql3 = "insert into your_db_name (name1,name2,filetitle,mime_type,file_size,upload_date) values (?)";
var date = new Date();
var values = [filename,nm+'.'+ext,filename,file.mimetype,file.size,date]
con.query(sql3,[values],(err,result)=>{
if(err){throw err}
console.log("Inserted")
})
}
})
return Promise
}
const savefiles = async (filesarray)=>{
for(const file of filesarray)
{
await savemulti(file)
}
return Promise.resolve(1)
}
app.post('/testfileupload',async (req,res)=>{
if(req.files)
{
console.log(req.files)
const file = req.files.Upload
try{
if(Array.isArray(file))
{
await savefiles(file).then(()=>{
res.status(200).send("File uploaded")
})
}
}catch(err){
return res.status(404).send('an error occured')
}
}else{
res.status(404).send('no file attached');
}
})

Front end:
<form method="POST" action=".../add-product" enctype="multipart/form-data">
<input multiple type="file" name="images" />
<input type="submit" />
</form>
Back end:
app.post('/add-product', async (req, res) => {
if (!req.files) {
return res.send({
success: false,
message: 'No image uploaded!'
});
}
const file = req.files.images;
const data = [];
function move(image) {
try { image.mv('public/images/' + image.name); }
catch (e) {
return res.send({
success: false,
message: 'upload error'
});
}
data.push({
name: image.name,
mimeType: image.mimetype,
size: image.size
});
}
Array.isArray(file) ? file.forEach((file) => move(file)) : move(file);
return res.send({ success: true, message: 'uploaded successfully', data });
});

Related

File not uploading in Express JS using Multer received fro Editor

I am getting the file using TinyMCE Editor. Using the paste plugin and uploading it using Express Server. I have tried using different things. But need to upload file received from TinyMCE editor
Here is my front-end Code:
function example_image_upload_handler(blobInfo, success, failure, progress) {
var xhr, formData;
localStorage.myfile = blobInfo.blob()
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', 'http://localhost:5000/api/upload');
xhr.upload.onprogress = function (e) {
progress(e.loaded / e.total * 100);
};
xhr.onload = function () {
var json;
if (xhr.status === 403) {
failure('HTTP Error: ' + xhr.status, { remove: true });
return;
}
if (xhr.status < 200 || xhr.status >= 300) {
failure('HTTP Error: ' + xhr.status);
return;
}
json = JSON.parse(xhr.responseText);
if (!json || typeof json.location != 'string') {
failure('Invalid JSON: ' + xhr.responseText);
return;
}
success(json.location);
};
xhr.onerror = function () {
failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
};
formData = new FormData();
formData.append('file', localStorage.myfile, blobInfo.filename());
xhr.send(formData);
};
const handleSubmit = async (e) => {
e.preventDefault();
console.log("hello");
example_image_upload_handler();
console.log(desc);
const newPost = {
username: user.username,
title,
desc,
};
if (file) {
const data = new FormData();
const filename = Date.now() + file.name;
data.append("name", filename);
data.append("file", file);
newPost.photo = filename;
try {
console.log("hello");
if (await axios.post("http://localhost:5000/api/upload", data)) {
// console.log("monu");
}
} catch (err) {
console.log(err);
}
}
try {
const res = await axios.post("http://localhost:5000/api/posts", newPost);
window.location.replace("/post/" + res.data._id);
} catch (err) {
console.log(err);
}
};
const handleEditorChange = (e) => {
console.log(
'Content was updated:',
setDesc(e.target.getContent())
);
}
return (
<div className="write">
{file && (
<img className="writeImg" src={URL.createObjectURL(file)} alt="" />
)}
<form className="writeForm" onSubmit={handleSubmit}>
<div className="writeFormGroup">
<label htmlFor="fileInput">
<i className="writeIcon fas fa-plus"></i>
</label>
<input
type="file"
id="fileInput"
style={{ display: "none" }}
onChange={(e) => setFile(e.target.files[0])}
/>
<input
type="text"
placeholder="Title"
className="writeInput"
autoFocus={true}
onChange={e => setTitle(e.target.value)}
/>
</div>
<Editor
apiKey="XXXXXXXXXXXXXXXXXXXXXXX"
initialValue="<p>Initial content</p>"
init={{
height: 500,
menubar: 'edit',
selector: 'textarea',
plugins: [
'advlist autolink lists link image',
'charmap print preview anchor help',
'searchreplace visualblocks code',
'insertdatetime media table paste wordcount',
'image imagetools paste'
],
images_upload_handler: example_image_upload_handler,
toolbar:
'undo redo | formatselect | bold italic | \
alignleft aligncenter alignright | \
bullist numlist outdent indent | image | help',
paste_data_images: true
}}
onChange={handleEditorChange}
/>
</div>
<button className="writeSubmit" type="submit">
Publish
</button>
</form>
</div>
);
Following is my express js upload API code:
const upload = multer({ storage: storage });
app.post("/api/upload", upload.single("file"), (req, res) => {
console.log("req");
console.log(req);
res.status(200).json("File has been uploaded");
});
Following is the error I am getting:
Please help me with the same.

NodeJS render html file with form not working on angular side

I am using ExpressJS with EJS template view engine. I am trying to show an HTML file on the angular component, but the form tag and its child input tag do not work on the angular side. They show only label data.
On NodeJS
agreementController.js
exports.getAgreementHtml = async (request, response, next) => {
const params = request.query
let reqPath = path.join(__dirname, '../agreements');
var agreementObj = {
user: { email: "example#gmail.com" }
}
// render domestic rent html
ejs.renderFile(reqPath + '/domestic_rent.ejs', agreementObj, {}, function (err, str) {
if (err !== null) {
responseObj.status = errorCodes.DATA_NOT_FOUND
responseObj.message = language.getMessage('NO_RECORD_FOUND')
response.send(responseObj)
return
}
responseObj.status = errorCodes.OK
responseObj.data = str
response.send(responseObj);
return;
});
}
domestic_rent.js
<form>
<div class="form-group">
<p><%= user.email %></p>
<div class="col-sm-offset-2 col-sm-10">
<input type="text" class="form-control" id="inputEmail3" placeholder="test" required name="test">
</div>
</div>
</form>
On Angular 8 Side
agreement-show.component.ts
getAgreementData() {
const params = {
id: this.agreementId
};
this.agreementService.getAgreementHtml(params).subscribe(
(result) => {
console.log('result agreement data::: ', result);
if (result.status !== 200) {
this.commonService.change.emit({ status: 'error', message: 'unknown error' });
return;
}
this.someHtml = result.data;
return;
}, (error) => {
console.log('error', error)
this.commonService.change.emit({ status: 'error', message: error.message });
}
);
}
agreement-show.component.html
<div [innerHTML]="someHtml"></div>
Output Attachment
By using ElementRef function we can add html runtime.
Please use following step:
#ViewChild('showitems') showitems: ElementRef;
const elemt: HTMLElement = this.showitems.nativeElement;
this.someHtml = result.data;
elemt.innerHTML = this.someHtml;

store images in postgresql from react using express multer

I'm trying to save images from my react app to backend using nodejs(express) and multer, I tried from these How to upload image using javascript fetch api and express multer
after I got the message file uploaded, how do you store it to database?
Here's the code in my react app
class UploadCover extends React.Component {
constructor(props){
super(props);
this.state={
id: this.props.location.state.id,
selectedFile : '',
imagePreviewUrl: ''
}
}
//handle image change
handleImageChange = (e) => {
e.preventDefault();
let reader = new FileReader();
let file = e.target.files[0];
reader.onloadend = () =>{
this.setState({
selectedFile:file,
imagePreviewUrl: reader.result
});
};
reader.readAsDataURL(file);
this.handleUploadCover(e.target.files[0]);
}
//upload cover
handleUploadCover = (file) => {
let form = new FormData(this.refs.myForm);
form.append('myImage', file);
fetch('http://localhost:3001/upload-cover', {
method: 'post',
header: { "Content-Type" : "application/json"},
body: form
})
.then( res =>res.json())
.then(data => console.log("data: ", data))
};
render() {
const { classes, ...rest } = this.props;
const { id, imagePreviewUrl } = this.state;
console.log("url: ", imagePreviewUrl)
let $imagePreview = null;
if(imagePreviewUrl){
$imagePreview = <img style={{width: "100%", height: "100%"}} src={imagePreviewUrl}/>;
}else{
$imagePreview = (
<div className={classes.previewText}>Please select cover</div>
);
}
return (
<div>
<HeaderHome/>
<div className={classNames(classes.main, classes.mainRaised)}>
<div className={classes.container}>
<div className={classes.storymargin}>
<h2 className={classes.title}>Upload Cover Story</h2>
<Card className={classes.uploadcontainer}>
<CardContent>
<div className={classes.imgPreview}>{$imagePreview}</div>
<form ref='myForm' encType='multipart/form-data'>
<input
accept="image/*"
className={classes.input}
id="raised-button-file"
multiple
type="file"
onChange={ e => this.handleImageChange(e)}
// ref='myForm'
/>
</form>
<label htmlFor="raised-button-file">
<Button component="span" className={classes.buttonupload}>
Choose Image
</Button>
</label>
</CardContent>
<CardActions>
<Link
to={{
pathname: "/create-chapter",
state: {id : id}
}}
>
<Button size="small" clor="primary" className={classes.buttonnextup}
onClick={ e => this.handleUploadCover(e) }
>
Next
</Button>
</Link>
</CardActions>
</Card>
</div>
</div>
</div>
<div className={classes.footer}>
<Footer />
</div>
</div>
);
}
}
and here's the backend
//set storage engine
const storage = multer.diskStorage({
destination: './public/uploads',
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
})
//Init upload
const upload = multer({
storage: storage,
limits: {fileSize: 1000000},
fileFilter: (req, file, cb) => {
checkFileType(file, cb);
}
}).single('myImage');
//Check File Type
checkFileType = (file, cb) => {
//Allowed ext
const filetypes = /jpeg|jpg|png|gif/;
//Check ext
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{
cb('Error: Images Only');
}
}
//upload cover story
app.post('/upload-cover', (req, res) => {
console.log('handling upload image');
upload( req, res, (err) => {
if(err){
console.log('first err', err);
res.send({
msg: err
});
}else{
if(req.file === undefined){
console.log('Error: No File Selected');
res.send({
msg: 'Error: No File Selected'
});
}else{
console.log('File Uploaded');
res.send({
msg: 'File Uploaded',
file: `uploads/${req.file.filename}`
});
}
}
});
});
and how can i send request with content type application/json and multipart/form-data at the same time through body request, I want to send form and id:this.state.id

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