Angular NodeJs multer upload img req.file is always undefined - mysql

I'm getting req.file as undefined. I have tried everything. I have searched for other solutions, but it's not a problem in input name="avatar" attr and upload.single("avatar").
Also, I'm getting an error in the console:
Error for image upload 400 - Bad Request
{"code":"ER_PARSE_ERROR","errno":1064,"sqlMessage":"You have an error
in your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near '?)' at line
1","sqlState":"42000","index":0,"sql":"INSERT INTO avatars (image)
VALUES(?)"}
I would say that it is because req.file is undefined.
Please, help me to understand what I'm doing wrong.
api.js:
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, "./assets/images/uploads");
},
filename: function(req, file, callback) {
callback(null, file.fieldname + "_" + Date.now() + "_" +
file.originalname);
}
});
var upload = multer({
storage: storage,
limits: {fileSize: 1000000},
fileFilter: function(req, file, cb) {
checkFileType(file, cb);
}
});
function checkFileType(file, cb) {
const filetypes = /jpeg|jpg|png|gif/;
const extname = filetypes.test(file.originalname.toLowerCase());
const mimetype = filetypes.test(file.mimetype);
if(extname && mimetype) {
return cb(null, true);
} else {
cb('Error: Images only');
}
}
router.post("/upload", upload.single('avatar'), function(req, res) {
console.log(req.file); // <- ALWAYS UNDEFINED
pool.getConnection(function(err, connection) {
if (err) throw err;
connection.query('INSERT INTO avatars (image) VALUES(?)', req.file,
function (error, results, fields) {
if(error){
console.log("Error: " + error);
res.status(400).send(error);
}
res.status(200).end(JSON.stringify(results));
connection.release();
if (error) throw error;
});
});
});
html:
<form enctype="multipart/form-data">
<input class="form-control"
(change)="onFileSelected($event)"
type="file" name="avatar">
<button type="submit" class="btn btn-danger float-right" (click)="onUpload()">Upload image</button>
</form>
ctrl:
onFileSelected(event) {
if(event.target.files.length > 0) {
this.uploadImage = <File>event.target.files[0];
}
}
onUpload() {
if(this.uploadImage) {
this.friendService.uploadFile(this.uploadImage)
.subscribe(
data => {
return true;
},
error => {
console.error('Error for image upload ' + error);
return false;
})
}
}
service:
uploadFile(file): Observable<any> {
return this.http.post(`${this.apiUrl}/upload`, file)
.map(res => res.json())
.catch(this.handleError);
}
db mysql avatars table:
Field - image
Type - blob
Null - NO
Key Default Extra - Empty

while uploading file it should be form data and content type should be multipart/form-data
For your reference: File Upload In Angular?.
I hope this will help you.

Related

TypeError: Cannot read properties of undefined (reading 'filename') in multer

I have a very similar problem with respect to this fellow community contributor. How do i produce multer error message in my postman I followed through the comments made by other users and it was successful! However, when i tried to post a image that is a jpg formatted image( which i managed to do before the editing), it now fails and state that TypeError: Cannot read property 'filename' of undefined.
// multer.js file
successfully setup multer
**please tell me why this error comes on my code and give me a solution**
const multer = require('multer');
const storage = multer.diskStorage({
fileSize: 1024*1024*2,
destination: function (req, file, cb) {
cb(null, './uploads')
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
cb(null, file.fieldname + '-' + uniqueSuffix)
}
})
const filter = function (req, file, cb) {
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
cb(null, true);
} else {
cb(new Error('unsupported files'), false)
}
}
var upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
},
fileFilter : filter
});
module.exports = upload;
//controller.js file
//create function
here's my logic to create a new user
exports.create = (req, res, next) => {
if (!req.body) {
res.status(400).send({ message: "content cannot be empty !!" })
return
}
let data = { name: req.body.name, description: req.body.description, brand_url:
req.body.brand_url, image_file: req.body.file.filename }; getting error here
let sql = "INSERT INTO influencer SET ?";
db.query(sql, data, (err, results) => {
if (err) throw err;
console.log('data inserted succesfully')
res.redirect('/admin');
});
}
//api.js file
//post API
router.post('/api/create', upload.single('image') ,controller.create) //when I am
sending file its throw back error undefined filename
Please make sure you have added enctype="multipart/form-data"
<form action="/api/create" enctype="multipart/form-data" method="post">
I have tested the codes & found the problem.
exports.create = (req, res, next) => {
if (!req.body) {
res.status(400).send({ message: "content cannot be empty !!" })
return
}
let data = {
name: req.body.name,
description: req.body.description,
brand_url: req.body.brand_url,
image_file: req.file.filename
}; // Remove "body", I have tested, it works well.
let sql = "INSERT INTO influencer SET ?";
db.query(sql, data, (err, results) => {
if (err) throw err;
console.log('data inserted succesfully')
res.redirect('/admin');
});
}

How to send HTML as a response in REST?

I have created an API in Nodejs. I have tried creating a call which returns HTML to display a site in the browser.
My Call looks like this:
router.get('/displayHTML', checkAccessToken, (req, res, next) => {
if (req.query.data === undefined) {
return res.status(900).json({
message: 'Data does not exist'
});
}
Data.find({ data: req.query.data}).exec()
.then(data => {
if (data.length < 1) {
return res.status(400).json({
message: "Nothing found"
});
}
// I need to return HTML here so the user sees something in his browser
return res.status(200).json({
data: data
});
}).catch(error => {
return res.status(500).json({
message: error
});
});
});
Check the fs_library: https://nodejs.org/docs/v0.3.1/api/fs.html
var http = require('http'),
lib = require('fs');
lib.readFile('./page.html', function (err, html) {
if (err) {
throw err;
}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(8000);
});

Image is not uploaded to defined folder in node.js

I have a small HTML template and what I want is to upload image from one location to another. After selecting and clicking on the upload button, response gives me "Uploaded successfully" But the image is not in the destination folder. Please look into the below code.
HTML
<form id="frmUploader" enctype="multipart/form-data" action="book/api/Upload/" method="post">
<input type="file" name="imgUploader" multiple />
<input type="button" name="submit" id="btnSubmit" value="Upload" onclick="upload()"/>
</form>
index.js
function upload() {
axios.post(baseUrlLocal+'/book/api/Upload', {headers: headers})
.then(response => {
console.log(response.data.success)
if (response.data.success) {
console.log("hi: "+response)
// $.notify("New Book is Added to your Library", "success");
}
})
.catch(function (error) {
console.log(error)
// $.notify("Please check all the details","warn");
});
}`
book.js
var Storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, "../public/images/");
},
filename: function(req, file, callback) {
callback(null, file.fieldname + "_" + Date.now() + "_" +
file.originalname);
}
});
var upload = multer({
storage: Storage
}).array("imgUploader", 3);
router.get("/image", function(req, res) {
res.sendFile(__dirname + "/index.html");
});
`router.post("/api/Upload", function(req, res) {
upload(req, res, function(err) {
if (err) {
return res.end("Something went wrong!");
}
return res.end("File uploaded sucessfully!.");
});
});`

req.file() isn't able to fetch multiple files

My html code is
<form action="/file_upload" method="POST" enctype="multipart/form-data">
<input type="file" name="photos" id="photos" accept='image/*' multiple>
<input type="submit" value="Upload" id="upload_my_photos" disabled>
</form>
In sails I am using
uploadFiles = req.file("photos");
This is only fetching just single file.
Edit : I would also like to save the individual files. Below is the code I am using but no files are getting uploaded:
req.file('photos').upload(function (err, uploadedPhotos) {
if (err) return res.serverError(err);
async.eachSeries(uploadedPhotos,
function (uploadedFile, callback) {
sails.log("upload file size and name is " + uploadedFile.size + " " + uploadedFile.filename);
req.file(uploadedFile).upload({
dirname: "path/to/directory",
// saveAs: function (file, cb) { cb(null, file.filename); }
},
function onUploadComplete(err, files) {
if (err) return res.serverError(err);
if (files.length === 0) {
return res.badRequest('No file was uploaded');
}
sails.log("files uploaded");
});
}, function (err) {
// if any of the saves produced an error, err would equal that error
if (err) {
console.log(err);
} else {
return res.status(200).send({ success: false, message: "failed to upload" });
}
});
});
Sails req.file() is representing an incoming multipart file upload from the specified field.
You need to subscribe to the request with a callback in which the uploaded files will be passed as an second argument:
req.file('photos').upload(function (err, uploadedPhotos){
if (err) return res.serverError(err);
return res.json({
message: uploadedPhotos.length + ' file(s) uploaded successfully!',
files: uploadedPhotos
});
});

Error POST http:abc/ 404 (Not Found) in angular2+ and nodejs

I am making a http request from my angular2+ code to database present in node.js file. The ajax call from angular2+ hits the controller.js file and then redirects to service.js file which has the connection to the database:
angular.ts ==> controller.js ==> service.js
From the database the service.js file gives the output to controller.js file and then answers the ajax call to angular.ts file:
service.js ==> controller.js ==> angular.ts
However, I am getting the error:
POST http://localhost:8096/dashboard/abcEntireSuccess1/ 404 (Not Found)
UPDATED
Cannot GET /dashboard/experianEntireSuccess1/
And one more issue -
UnauthorizedError: No authorization token was found
And one more issue -
After coming back from the hit in service.js which has the data i want ==> to => controller.js , here the data is acquired is undefined. As seen below -
The output on Nodejs -
output -
service.js
closed connection
yessss [ RowDataPacket { ....
controller.js
we are coming back to controller undefined
some error occured of abcEntireSuccess1
My Entire Code:
UPDATED
abc.component.ts
viewAbcEntireSuccess1() {
var url = config.url;
var port = config.port;
this.http.post("http://" + url + ":" + port + "/dashboard
/abcEntireSuccess1/", this.emptyObj
, { headers: new Headers({ 'Authorization': 'Bearer ' +
localStorage.getItem('Token') }) })
.map(resultConnection => this.resultConnection =
resultConnection.json(), )
.subscribe((res: Response) => {
this.records = res;
this.resultConnectionlength = this.resultConnection.length;
});
}
abc.controller.js
router.post('/experianEntireSuccess1',experianEntireSuccess1);
module.exports = router;
function abcEntireSuccess1(req, res) {
dashboardService.abcEntireSuccess1(req.body)
.then(function (result) {
console.log("we are coming back to controller",result)
if (result.length > 0) {
console.log("we get data in node of abcEntireSuccess1 ::
" + Object.values(result));
console.log(result.length + " record found ");
res.send(result);
}
else {
result=[];
res.send(result);
}
})
.catch(function (err) {
res.status(400).send(err);
console.log("some error occured of abcEntireSuccess1");
});
}
abc.service.js
async function abcEntireSuccess1() {
console.log("function called")
const db = new Database();
await db.query(`select * from TRANSACTION_PAYLOAD where INTERFACE_NAME
= 'Abc' AND (STATUS ='SUCCESS_RESPONSE')`
).then(rows => {
console.log("closed connection");
console.log("yessss",rows)
return rows;
});
};
class Database {
constructor() {
this.connection = mysql.createConnection({
host: "127.0.0.1",
user: "abc",
password: "abc",
database: "DB"
});
}
query(sql, args) {
console.log("sql is", sql)
return new Promise((resolve, reject) => {
this.connection.query(sql, (err, rows) => {
console.log("connection function called")
if (err) {
console.log("error is", err)
return reject(err);
}
console.log("rows are",rows);
resolve(rows);
});
});
}
close() {
console.log("calling connection close")
return new Promise((resolve, reject) => {
console.log("called connection close")
this.connection.end(err => {
if (err){
return reject(err);
}
resolve();
});
});
}
}