Upload Image data showing {} in Nodejs from ANgular js - node.js

I am wrking on nodejs . i got response from frontend post request. all dataa is getting but upload file data showing null. {}
Pleasse see images
enter image description here
enter image description here
const imageUpload = multer({
storage: multer.diskStorage({
destination: function (req, file, cb) {
console.log("asd");
cb(null, "Attachments/");
},
filename: function (req, file, cb) {
cb(null, new Date().valueOf() + "_" + file.originalname);
},
}),
limits: { fileSize: 10000000 },
fileFilter: function (req, file, cb) {
if (
!file.originalname.match(
/\.(jpg|JPG|webp|jpeg|JPEG|png|PNG|gif|GIF|pdf|PDF|docx|doc)$/
)
) {
req.fileValidationError = "Only Image, PDF and Word files are allowed!";
return cb(null, false);
} else {
req.fileValidationError = "";
}
cb(null, true);
},
});
---
// Add Property Details
app.post('/addproperty', imageUpload.single("image"), (req, res) => {
console.log("vicky", req.body.body.file);
if (req.fileValidationError != "") {
throw req.fileValidationError;
}
console.log(req.body.body)
req.body.body = req.body;
let qrr = 'INSERT INTO listproperty (Type, plotNo, location, sqft, sellType, facing, price, BedRoom, BAthRoom, Parking, date, Description, src)VALUES("'+req.body.Type+'","'+req.body.plotNo+'","'+req.body.location+'","'+req.body.sqft+'","'+req.body.sellType+'","'+req.body.facing+'", "'+req.body.price+'","'+req.body.BedRoom+'","'+req.body.BAthRoom+'","'+req.body.Parking+'","'+req.body.date+'","'+req.body.Description+'","'+req.body.src+'");'
db.query(qrr, (err1, res1) => {
if(err1)console.log(err1);
else {
res.send({
message: 'Data inserted',
body:res1
})
}
})
});
newProperty : any = new FormGroup({
Type: new FormControl([Validators.required]),
sellType: new FormControl([Validators.required]),
facing: new FormControl([Validators.required]),
src: new FormControl(''),
plotNo: new FormControl('', Validators.required),
location: new FormControl('', Validators.required),
price: new FormControl(Validators.required),
sqft: new FormControl(Validators.required),
BedRoom: new FormControl(Validators.required),
BAthRoom: new FormControl(Validators.required),
Parking: new FormControl(Validators.required),
Description: new FormControl('', Validators.required),
date: new FormControl([Validators.required]),
});
// On file Select
onChange(event: any) {
this.newProperty.value.src = event.target.files;
//console.log(event);
// this.file = event.target.files[0];
}
ngOnInit(): void {
this.getPropertyType()
this.sellType = this.data.getSellType();
let x = this.route.snapshot.paramMap.get('property')
// if (x) {
// var d=this.data.getSingleData(x)
// console.log(d);
// setTimeout(() => {
// this.newProperty.patchValue(d)
// // this.newProperty.setControl('src')
// }, 1000);
// }
}
getPropertyType() {
console.log("res", this.sql.getPlotType());
this.sql.getPlotType().subscribe((res)=>{
console.log(res);
for (let i = 0; i < res.length; i++) {
this.plotType.push( res[i].propertyType);
}
// this.plotType =res
});
}
addNew() {
if (this.newProperty.invalid) {
alert('fill all details');
return;
}
var data = [];
//JSON.parse(this.newProperty.value)
this.sql.addplotdata(this.newProperty.value).subscribe((res)=>{
console.log(res);
for (let i = 0; i < res.length; i++) {
data.push( res);
}
console.log("data");
// this.plotType =res
});
console.log(this.newProperty.value);
// this.data.addData(this.newProperty.value);
//this.newProperty.reset();
this.router.navigate(['add-property']);
}
addplotdata(value: any): Observable<any> {
return this.http.post(this.addPropUrl, {value, "image" :value.src});
} // Backend.ts
Hello, I am wrking on nodejs . i got response from frontend post request. all dataa is getting but upload file data showing null. {} Pleasse see images
Hello, I am wrking on nodejs . i got response from frontend post request. all dataa is getting but upload file data showing null. {} Pleasse see images
Hello, I am wrking on nodejs . i got response from frontend post request. all dataa is getting but upload file data showing null. {} Pleasse see images

Related

Node.js Sendgrid attaching pdf files upto 7 MB crashes the server

I have a Node.js + Express application running on EC2 instance. Part of that application is to send mass email to all its users (by the admin) with the ability to attach files (max 5 files allowed).
Recently we tested it by attaching three pdf files roughly the size of 2.5 MB each. When the send button is pressed the application keeps spinning before culminating to 504 Gateway Timeout error. I feel that maybe the sendgrid code is unable to process the attachments and the node server crashes taking down the EC2 with it. When this happens the only way for me is to stop the ec2 instance and then start it again. Rebooting does not help.
Here is the code
router.js
var fs = require('fs');
var multer = require('multer');
const uploadsDir = './uploads';
// SET STORAGE
var storage = multer.diskStorage({
destination: function (req, file, cb) {
if (!fs.existsSync(uploadsDir)){
fs.mkdirSync(uploadsDir);
}
cb(null, uploadsDir);
},
filename: function (req, file, cb) {
cb(null, file.originalname);
}
});
var upload = multer({ storage: storage });
router.post('/send', upload.array('files', 5), async (req, res) => {
let subject = req.body.subject;
let message = req.body.message;
let result = message.replace(/(\r\n|\r|\n)/g, '<br>');
let bccReceiverList = [];
let whereCondition = {
isActive: true
};
let attachments = [];
if(req.files && req.files.length > 0) {
req.files.forEach(file => {
attachments.push({
filename: file.originalname,
type: file.mimetype,
uploadPath: req.app.get('uploads')
});
});
}
let receiverUsers = await User.findAll({});
//find to whom we are sending the email to
for (let index = 0; index < receiverUsers.length; index++) {
const user = receiverUsers[index];
emailHandler.sendEmail(
{
receiver: user.email,
bccReceiver: bccReceiverList,
templateId: process.env.EMAIL_BLAST_TEMPLATE,
attachments: attachments.length > 0 ? attachments : []
},
{
subject: subject,
message: result
},
data => {}
);
}
if(req.files && req.files.length > 0) {
req.files.forEach(file => {
fs.unlink(req.app.get('uploads') + '/' + file.originalname, function (err) {
if (err) {
console.error(err);
}
console.log('File has been Deleted');
res.send('file was deleted');
});
});
}
res.redirect('back');
});
then in the actual email handler function
var sg = require('#sendgrid/mail');
var fs = require('fs');
sg.setApiKey(process.env.SENDGRID_API_KEY);
exports.sendEmail = async function(email, payload, callback) {
let msg = {
to: email.receiver,
from: {email: 'admin#myapp.com', name: 'My App'},
subject: email.subject,
templateId: email.templateId,
dynamic_template_data: payload
};
//Buffer.from(fileContent).toString('base64')
if(email.attachments != null && email.attachments.length > 0) {
try {
let attachmentObjects = [];
for (let index = 0; index < email.attachments.length; index++) {
const attachment = email.attachments[index];
const fileContent = fs.readFileSync(attachment.uploadPath + '/' + attachment.filename);
attachmentObjects.push({
content: Buffer.from(fileContent).toString('base64'),
filename: attachment.filename,
type: attachment.mimetype,
disposition: "attachment"
});
}
msg.attachments = attachmentObjects;
} catch (error) {
console.log(error);
callback({status: 500, message: 'Error while attaching files to email: ' + error.message});
}
}
if(email.hasOwnProperty('ccReceiver')) {
if(email.ccReceiver != null) {
msg.cc = email.ccReceiver;
}
}
if(email.hasOwnProperty('bccReceiver')) {
if(email.bccReceiver.length > 0) {
msg.bcc = email.bccReceiver;
}
}
sg.send(msg).then(() => {
console.log('---- email sent successfully');
// delete the attachment files from the uploads folder
if(email.attachments != null && email.attachments.length > 0) {
for (let index = 0; index < email.attachments.length; index++) {
const attachment = email.attachments[index];
fs.unlink(attachment.uploadPath + '/' + attachment.filename, function (err) {
if (err) {
console.error(err);
}
console.log('File has been Deleted');
});
}
}
callback({status: 200, message: 'Email Sent Successfully'});
}).catch(error => {
//Log friendly error
console.error('error-------- : ' + error.toString());
//Extract error msg
const {
message,
code,
response
} = error;
//Extract response msg
const {
headers,
body
} = response;
callback({status: 500, message: 'Error while sending email: ' + error.message});
});
};
I even tried just attaching one pdf file (2.5 MB) to the email and it still failed. When I perform this same test with files with lesser size then it works smoothly. I am not really sure how to solve this problem.

Fetching images from mongoDB using mongoose, nodeJS, express, react

I have been working off the following guide to upload and fetch images to and from mongoDB and am having issues getting the images to redisplay on the react page after being fetched. I think the issue is with the HTML img src but it could be further up the line so ill walk through everything I have done.
server.js
// -------------------- Mongoose schema -------------------
var imageSchema = new mongoose.Schema({
img:
{
data: Buffer,
contentType: String
}
});
const offeringSchema = new mongoose.Schema({
image: [imageSchema]
});
const Image = mongoose.model("Image", imageSchema)
const Offering = mongoose.model("Offering", offeringSchema);
// -------------------- Set up Multer -------------------
const storage = multer.diskStorage({
destination: './public/uploads/images',
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() +
path.extname(file.originalname));
}
});
// -------------------- Post Offering Data -------------------
// upload featured offering image
app.post('/admin/OfferingFeatureImage', upload.single('featuredImage'), function (req, res) {
if (req.isAuthenticated()) {
if (req.user.userData[0].admin === true) {
console.log(req.file);
var newImage = new Image();
newImage.img.data = fs.readFileSync(req.file.path)
newImage.img.contentType = 'image/png';
Offering.updateOne({ _id: req.body.offeringID }, {image:[newImage]}, function (err) {
if (err) {
console.log(err)
} else {
res.redirect("/Admin/Offerings");
}
})
} else {
res.send("not-privileged")
}
} else {
res.redirect("/login")
};
});
// -------------------- Get Offering Data -------------------
app.get("/data/allInvestment", function (req, res) {
Offering.find({}, function (err, foundOfferings) {
if (err) {
res.send(err);
} else {
res.send(foundOfferings);
};
});
});
On the client side i am able to get the offering data and see the img data appears to be present
client side data
{props.investmentsData.image[0] !== undefined &&
<img src={"data:" + props.investmentsData.image[0].img.contentType + ";base64," + props.investmentsData.image[0].img.data.toString('base64')} className="card-img-top" alt="..."></img>
}
outcome

How to upload image files in Postman and echo back the same image using Express and Multer

I am trying to upload a product using postman and anytime I submit; it sends back all the data with the image undefined as shown in this screenshot:
My controller file:
const gameRepository = require("../routes/repository")
exports.createGame = async (req, res, next) => {
try {
const PORT = 8000;
const hostname = req.hostname;
const url = req.protocol + '://' + hostname + ':' + PORT + req.path;
const payload = ({
name: req.body.name,
price: req.body.price,
category: req.body.category,
gameIsNew: req.body.gameIsNew,
topPrice: req.body.topPrice,
isVerOrient: req.body.IsVerOrient,
description: req.body.description,
image: url + '/imgs/' + req.path
});
let eachGame = await gameRepository.createGame({
...payload
});
console.log(req.body)
res.status(200).json({
status: true,
data: eachGame,
})
} catch (err) {
console.log(err)
res.status(500).json({
error: err,
status: false,
})
}
}
repository.js:
const Game = require("../models/gameModel");
exports.games = async () => {
const games = await Game.find();
return games;
}
exports.gameById = async id => {
const game = await Game.findById(id);
return game;
}
exports.createGame = async payload => {
const newGame = await Game.create(payload);
return newGame;
}
exports.removeGame = async id => {
const game = await Game.findById(id);
return game;
}
Multer.js:
const multer = require("multer");
const path = require("path");
// checking for file type
const MIME_TYPES = {
'imgs/jpg': 'jpg',
'imgs/jpeg': 'jpeg',
'imgs/png': 'png'
}
// Image Upload
const storage = multer.diskStorage({
destination: (req, file, cb ) => {
cb(null, path.join('../imgs'));
},
filename: (req, file, cb) => {
const name = file.originalname.split('').join(__);
const extension = MIME_TYPES[file.mimetype];
cb(null, name + new Date().toISOString() + '.' + extension);
}
});
module.exports = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 6
},
})
I am not sure about where I went wrong, that is why I need an external eye to help locate where the fault is coming from.
I have a feeling that I need to use body-parser or navigate into the image folder correctly, or multi-part form, I am not sure.
after many try and fail I finally figured it out.
turns out it has compatibility issues depending on your OS.
I use windows 10 and this resolved the issue for me
Here is my working code:
multer.js
const multer = require("multer");
const path = require("path");
// checking for file type
const MIME_TYPES = {
'image/jpg': 'jpg',
'image/jpeg': 'jpeg',
'image/png': 'png'
}
// Image Upload
const storage = multer.diskStorage({
destination: (req, file, cb ) => {
cb(null, ('storage/imgs/'));
},
filename: (req, file, cb) => {
const extension = MIME_TYPES[file.mimetype];
// I added the colons in the date of my image with the hyphen
cb(null, `${new Date().toISOString().replace(/:/g,'-')}.${extension}`);
}
});
module.exports = multer({
storage: storage
})
In my controller.js
const gameRepository = require("../routes/repository");
exports.createGame = async (req, res, next) => {
try {
const payload = {
name: req.body.name,
price: req.body.price,
category: req.body.category,
gameIsNew: req.body.gameIsNew,
topPrice: req.body.topPrice,
isVerOrient: req.body.IsVerOrient,
description: req.body.description,
image: req.file.filename,
};
let eachGame = await gameRepository.createGame({
...payload,
});
res.status(200).json({
status: true,
data: eachGame,
});
} catch (err) {
console.log(err);
res.status(500).json({
error: err,
status: false,
});
}
};
exports.getGames = async (req, res) => {
try {
let games = await gameRepository.games();
res.status(200).json({
status: true,
data: games,
});
} catch (err) {
console.log(err);
res.status(500).json({
error: err,
status: false,
});
}
};
exports.getGameById = async (req, res) => {
try {
let id = req.params.id;
let gameDetails = await gameRepository.gameById(id);
req.req.status(200).json({
status: true,
data: gameDetails,
});
} catch (err) {
res.status(500).json({
status: false,
error: err,
});
}
};
exports.removeGame = async (req, res) => {
try {
let id = req.params.id;
let gameDetails = await gameRepository.removeGame(id);
res.status(200).json({
status: true,
data: gameDetails,
});
} catch (err) {
res.status(500).json({
status: false,
data: err,
});
}
};
:
Postman output
Thanks to this great community.

file upload not working in react native with multipart form data api nodejs

I am trying to upload image file with react native, by using nodejs multipart api, but the file is not getting sent from the FE. If I console req.files its undefined at server side. Here is my react native code:
var options = {
title: 'Select Image',
storageOptions: {
skipBackup: true,
path: 'images'
}
};
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
console.log('User selected a file form camera or gallery', response);
const data = new FormData();
data.append('name', 'avatar');
data.append('file', {
uri: response.uri,
type: response.type,
name: response.fileName
});
const config = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: data,
};
fetch("http://myapi.com/api/v1/user", config)
.then((checkStatusAndGetJSONResponse) => {
console.log(checkStatusAndGetJSONResponse);
}).catch((err) => { console.log(err) });
}
}
)
and Nodejs code:
const storage = multer.memoryStorage({
destination:(req, file, callback) => {
callback(null, '')
}
});
const upload = multer({ storage: storage }).array('file');
upload(req,res,(err) => {
if(err) {
console.log('ERROR: ',err);
return res.end("Error uploading file.");
}else{
console.log('REQUEST: ',req.files);
}
});
I am not able to upload image with some user data, please let me know what am doing wrong here
Thanks
as you are sending form data in body, it will only hold that form data.
if you want to send form data plus some other data, then try to append form data in another object and then append other data in same object with key value pair.
I have created user register form in which I have some input fields and profile upload.
For upload I have used "ngx-file-drop".
like:-
const body = {};
body['formData'] = formValues;
body['fileData'] = this.fileDataArray;
In this the ts code is like below.
dropped(files: NgxFileDropEntry[]) {
this.fileError = false;
this.files = [];
this.files = files;
for (const droppedFile of files) {
// Is it a file?
if (droppedFile.fileEntry.isFile && this.isFileAllowed(droppedFile.fileEntry.name)) {
this.filesArray.push(droppedFile);
const fileEntry = droppedFile.fileEntry as FileSystemFileEntry;
const formData: FormData = new FormData();
fileEntry.file((file: File) => {
});
fileEntry.file((file: File) => {
this.dropFilePath.push(droppedFile.relativePath);
// append form data
formData.append('upload', file, droppedFile.relativePath);
this.dropFile.push(file);
this.dropFileFlag = true;
});
} else {
// It was a directory (empty directories are added, otherwise only files)
const fileEntry = droppedFile.fileEntry as FileSystemDirectoryEntry;
this.dropFilePath = [];
this.dropFile = [];
this.files = [];
this.toaster.error('only this file are allowed : [".jpg", ".jpeg",".gif",".png"]', 'Error', {
positionClass: 'toast-top-full-width',
});
break;
}
}
}
and html code is.
<ngx-file-drop [disabled]="isPreview ? true : null" dropZoneLabel="Drop files here" (onFileDrop)="dropped($event)" (onFileOver)="fileOver($event)"(onFileLeave)="fileLeave($event)">
<ng-template ngx-file-drop-content-tmp let-openFileSelector="openFileSelector">
<span [attr.disabled]="isPreview ? true : null" class="btn">Drop files here or</span>
<span [attr.disabled]="isPreview ? true : null" (click)="openFileSelector()" class="btn btn-link">click to upload</span>
</ng-template>
</ngx-file-drop>
and on form submit you can do like this.
onSubmit() {
this.submitted = true;
if (this.form.invalid || (this.submitted && this.fileError)) {
this.toaster.error('Invalid form data..!!', 'ERROR');
return;
}
const formData = this.form.value;
this.fileDataArray.push(formData.getAll('upload'));
console.log('this.fileDataArray-------->', this.fileDataArray);
const body = {};
body['formData'] = formData;
body['fileData'] = this.fileDataArray;
console.log('body------>', body);
// call below your api function
}

Upload images from iOS is too slow

My React-Native iOS front-end can not upload images to my Node.JS (Express + Multer) back-end.
My front-end is React Native Android & iOS. The Android version works fine with no issues, however, uploading images from and iOS device doesn't work most of the time.
Once the upload request is sent, I can see the image file is added in FTP, however, very slowly, like a few KB every second. An image of 500 KB may take 3 minutes or more till the request times out. The file is added to the server partially and I can see change in size with each refresh.
Some [iOS] devices had no issues at all, uploads fast, however, the vast majority of devices are running into this issue.
No connectivity issues. The same host and network work perfectly with Android. Same with some iOS devices.
This is not limited to a specific iOS version or device. However, the devices who had the issue always have it, and those that don't, never have it.
How can I troubleshoot this?
POST request:
router.post('/image', (req, res) => {
console.log('image')
upload(req, res, (error) => {
if (error) {
console.log(error)
return res.send(JSON.stringify({
data: [],
state: 400,
message: 'Invalid file type. Only JPG, PNG or GIF file are allowed.'
}));
} else {
if (req.file == undefined) {
console.log('un')
return res.send(JSON.stringify({
data: [],
state: 400,
message: 'File size too large'
}));
} else {
var CaseID = req.body._case; // || new mongoose.Types.ObjectId(); //for testing
console.log(req.body._case + 'case')
var fullPath = "uploads/images/" + req.file.filename;
console.log(fullPath);
var document = {
_case: CaseID,
path: fullPath
}
var image = new Image(document);
image.save(function(error) {
if (error) {
console.log(error)
return res.send(JSON.stringify({
data: [],
state: 400,
message: 'bad request error'
}));
}
return res.send(JSON.stringify({
data: image,
state: 200,
message: 'success'
}));
});
}
}
});
});
Upload.js:
const multer = require('multer');
const path = require('path');
//image upload module
const storageEngine = multer.diskStorage({
destination: appRoot + '/uploads/images/',
filename: function (req, file, fn) {
fn(null, new Date().getTime().toString() + '-' + file.fieldname + path.extname(file.originalname));
}
});
const upload = multer({
storage: storageEngine,
// limits: {
// fileSize: 1024 * 1024 * 15 // 15 MB
// },
fileFilter: function (req, file, callback) {
validateFile(file, callback);
}
}).single('image');
var validateFile = function (file, cb) {
// allowedFileTypes = /jpeg|jpg|png|gif/;
// const extension = allowedFileTypes.test(path.extname(file.originalname).toLowerCase());
// const mimeType = allowedFileTypes.test(file.mimetype);
// if (extension && mimeType) {
// return cb(null, true);
// } else {
// cb("Invalid file type. Only JPEG, PNG and GIF file are allowed.")
// }
var type = file.mimetype;
var typeArray = type.split("/");
if (typeArray[0] == "image") {
cb(null, true);
}else {
cb(null, false);
}
};
module.exports = upload;
React Native Upload function:
pickImageHandler = () => {
ImagePicker.showImagePicker(this.options1, res => {
if (res.didCancel) {
} else if (res.error) {
} else {
this.setState({upLoadImage:true})
var data = new FormData();
data.append('image', {
uri: res.uri,
name: 'my_photo.jpg',
type: 'image/jpg'
})
data.append('_case',this.state.caseID)
fetch(url+'/image'
, {method:'POST',
body:data
}
)
.then((response) => response.json())
.then((responseJson) =>
{
this.setState(prevState => {
return {
images: prevState.images.concat({
key: responseJson._id,
src: res.uri
})
}
}
)
this.setState({upLoadImage:false})
})
.catch((error) =>
{
alert(error);
});
}
}
)
}
Any suggestions?
Thanks
I saw your answer from UpWork
please try this way,
I'm using API Sauce for API calls
export const addPartRedux = (data) => {
return (dispatch, getState) => {
console.log('addPArtREdux', data);
const values = {
json_email: data.token.username,
json_password: data.token.password,
name: data.text ? data.text : '',
car: data.selected.ID,
model: data.selectedSub.ID,
make_year: data.selectedYear,
type: data.type,
ImportCountry: data.import_image ? data.import_image : '',
FormNumber: data.number ? data.number : '',
do: 'insert'
};
const val = new FormData();
Object.keys(values).map((key) =>
val.append(key, values[key])
);
if (data.imageok) {
val.append('image', {
uri: data.image.uri,
type: data.image.type,
name: data.image.name
});
}
dispatch(loading());
api
.setHeader('Content-Type', 'multipart/form-data;charset=UTF-8');
api
.post('/partRequest-edit-1.html?json=true&ajax_page=true&app=IOS',
val,
{
onUploadProgress: (e) => {
console.log(e);
const prog = e.loaded / e.total;
console.log(prog);
dispatch(progress(prog));
}
})
.then((r) => {
console.log('Response form addPartRedux', r.data);
if (r.ok === true) {
const setting = qs.parse(r.data);
dispatch(addpart(setting));
} else {
dispatch(resetLoading());
dispatch(partstError('Error Loading '));
}
})
.catch(
(e) => {
console.log('submitting form Error ', e);
dispatch(resetLoading());
dispatch(partstError('Try Agin'));
}
);
};
};

Resources