files not uploading sails js - javascript

So, when I upload file it doesn't me show any error, it just doesn't upload the file and I get the message '0 files uploaded successfully, I do get the record in database for each uploaded item
So, here's the input form
<form action='./make' method="post">
<input type="file" name="vid"> <br>
<input type="text" name="name"> <br>
<input type="hidden" name="_csrf" value="<%= _csrf %>">
<input type="hidden" name="ownerID" value="<%= req.session.User.id %>">
<input type="submit" value="add video">
</form>
And this is the 'make' action:
make: function (req, res, next) {
Video.create(req.params.all(), function videoCreated (err,video) {
console.log("create video");
// if(err) return next(err);
req.file('vid').upload({
dirname: './assets/images'
}, function (err, uploadedFiles) {
if (err) return res.negotiate(err);
return res.json({
message: uploadedFiles.length + ' file(s) uploaded successfully!'
});
});
if(err){
console.log(err);
req.session.flash = {
err: err
}
return res.redirect('/user/new');
}
});
}

Try with this:
index.ejs
<form enctype="multipart/form-data" action="epale" method="post">
<input type="file" id="archivo" name="archivo">
<input type="submit" value="Enviar">
</form>
IndexController.js
epale: function (req, res) {
//return res.send('Hi there!');
if (req.method === 'GET')
return res.json({ 'status': 'GET not allowed' });
// Call to /upload via GET is error
var uploadFile = req.file('archivo');
console.log(uploadFile);
uploadFile.upload({
dirname: '../../assets/images',
saveAs: function(file, cb) {
cb(null, file.filename);
}
}, function onUploadComplete(err, files) {
// Files will be uploaded to .tmp/uploads
if (err) return res.serverError(err);
// IF ERROR Return and send 500 error with error
console.log(files);
res.json({ status: 200, file: files });
});
},
routes.js
'/': {
view: 'homepage'
},
'/index': {
view: 'index'
},
'/epale': {
controller: "Index",
action: "epale",
},
Revised (05-11-2016) in: http://maangalabs.com/blog/2014/08/12/uploading-a-file-in-sails/

Related

MONGODB findOne() needs a variable

My function is set to find email brought from /login POST method, but I am failing to declare the variable properly, what is the variable to be inserted into the findOne form on app.get('/data')?
I have:
app.post('/login', function (req, res) {
//console.log(req.body);
const uri = "mongodb+srv://<PRIVATE INFO>.eapnyil.mongodb.net/?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
const users = client.db("data").collection("users");
users.findOne({email:req.body.email},function(err,data){
if(data){
if(data.password==req.body.password){
//console.log("Logged In.");
console.log('Email in DB is: ' + data.email);
console.log('Email in form is: ' + req.body.email);
//res.send({"Success":"Success!"});
res.redirect('/data');
}else{
res.send({"Failed with":"Wrong password!"});
}
}else{
res.send({"Try again":"Email not registered!"});
}
});
});
app.get('/data', (req, res) => {
const users = client.db("data").collection("users");
users.findOne({unique_id:req.session.id})((err, result) => {
if (err) return console.log(err)
// renders index.ejs
res.render('pages/data.ejs', {users: result})
})
});
and on the login.ejs file the following:
<p>Login</p>
</div>
<div class="form-group">
<form id="form" method="POST" action="/login">
<input type="text" name="email" placeholder="E-mail" required="" class="form-control"><br/>
<input type="password" name="password" placeholder="Password" required="" class="form-control"><br/>
<input type="submit" value="Login" class="btn btn-success">
</form>
</div>
Not sure why you are redirecting to the /data method when you already have the user to pass to the view.
Try to redirect in /login directly:
app.post('/login', function (req, res) {
//console.log(req.body);
const uri =
'mongodb+srv://<PRIVATE INFO>.eapnyil.mongodb.net/?retryWrites=true&w=majority';
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverApi: ServerApiVersion.v1,
});
const users = client.db('data').collection('users');
users.findOne({ email: req.body.email }, function (err, data) {
if (data) {
if (data.password === req.body.password) {
res.render('pages/data.ejs', {users: data})
} else {
res.send({ 'Failed with': 'Wrong password!' });
}
} else {
res.send({ 'Try again': 'Email not registered!' });
}
});
});
Also, I suggest you hash the password that you store in the database using libraries like bcrypt.
Storing credentials in plain text is a bad security practice.
app.get('/data', (req, res) => {
const users = client.db("data").collection("users");
users.findOne({unique_id:req.session.id},((err, result) => {
if (err) return console.log(err)
// renders index.ejs
res.render('pages/data.ejs', {users: result})
}))
});
there is a syntax error after {unique_id:req.session.id}, replace ')' for ',' and close ')' correctly

XHR failed loading: POST on AJAX request (in React)

I don't think React has anything to do with this, but just in case, that's what I'm working in. I'm receiving the error XHR failed loading: POST when submitting an AJAX request to /login. I am trying to create a login route using Passport JS, and I know that the route is receiving the data because it will console.log as { email: 'myemail', password: 'mypassword' } and typeof returns object.
this.handleLoginSubmit = () => {
let xml = new XMLHttpRequest();
xml.open("POST", "/login", true);
xml.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xml.send(JSON.stringify({email: this.state.email, password: this.state.password}));
xml.onreadystatechange = () => {
if(xml.readyState === 4) {
console.log('here')
console.log(xml.response);
}
}
}
EDIT Here is the route:
router.post('/login', emailToLowerCase, function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
console.log('error')
return next(err);
}
if (!user) {
return console.log('no user!')
}
req.logIn(user, function(err) {
if (err) return next(err);
console.log('logging in')
return res.send(req.user)
});
})(req, res, next);
});
EDIT Here is the form:
<form id='login-form' className="small-form" className='nav-div' onSubmit={props.handleLoginSubmit}>
<div className='nav-div'>
<li className="nav-item">
<input type="email" required name="email" placeholder='Email' className='form-control' value={props.email} onChange={(e) => props.handleEmailChange(e.target.value)}/>
</li>
<li className="nav-item">
<input type="password" required name="password" placeholder='Password' className='form-control' value={props.password} onChange={(e) => props.handlePasswordChange(e.target.value)}/>
</li>
<li className='nav-item'>
<input type='submit' value='Login' />
</li>
</div>
In your code:
if (!user) {
return console.log('no user!')
}
You are not sending any response to UI. Not sure how the next(err) processes the response, but at lease in case user is not found you want to send some error back to the client, like:
if (!user) {
console.log('no user!');
return res.status( 404 ).json({ message: 'User not found' });
}

POST http://localhost:3000/upload 500 (Internal Server Error)

I have an error when I send data from client side (angular.js) to server side (node.js).
I created a form that the user insert data then my controller get the data and sent it to the server to save the data in mongoose and s3(amazon).
I must say that it works fine - I mean I can save all the information I need, I can see it in my DB and I can see the image on s3
but, I get an error : POST http://localhost:3000/upload 500 (Internal Server Error)
my html form:
<html ng-app="mymed">
<head>
<title>insert</title>
</head>
<body ng-controller="tryController">
<main>
<body>
<form class="form-group" enctype="multipart/form-data" method="POST" action="http://localhost:3000/upload">
<label for="inputEmail3" class="col-sm-2 control-label">Title:</label>
<input class="form-control" type="text" placeholder="Title" ng-model="Title" name="Title" required></input>
</div>
<div class="col-sm-10">
<br>
<input type="file" name="file" accept="image/*" ng-modle="file"></input>
</div>
</div>
<input type="submit" class="btn btn-default" name="send" ng-click="createInsert()"></input>
</form>
.....
<script src="js/appController.js"></script>
my controller:
mymedical.controller('tryController',['$scope','$http','$cookies', function($scope,$http,$cookies){
$scope.createInsert = function(){
var data = {};
data.Title = $scope.Title;
data.file = $scope.file;
$http.post('http://localhost:3000/upload', JSON.stringify(data)).then() //callback
}
}]);
sever side:
exports.saveDatatry=function(request, response){
console.log(request.body);
var file = request.files.file;
var hash = hasher();
var stream = fs.createReadStream(file.path)
var mimetype = mime.lookup(file.path);
console.log(stream);
var req;
if (mimetype.localeCompare('image/jpeg')
|| mimetype.localeCompare('image/pjpeg')
|| mimetype.localeCompare('image/png')
|| mimetype.localeCompare('image/gif')) {
req = client.putStream(stream, hash+'.png',
{
'Content-Type': mimetype,
'Cache-Control': 'max-age=604800',
'x-amz-acl': 'public-read',
'Content-Length': file.size
},
function(err, result) {
var savePerTry = new personal({
Title: request.body.Title,
file: req.url
});
savePerTry.save(function(error, result) {
if (error) {
console.error(error);
} else {
console.log("saved!");
response.redirect('http://localhost:8080/tryinsert.html');
};
})
});
} else {
console.log(err);
}
}
What I need to do?
Thanks,
Here's your problem:
function(err, result) {
var savePerTry = new personal({
Title: request.body.Title,
file: req.url
});
Every time you write something like:
function(err, result) {
then the very next line should be:
if (err) {
// ...
}
When you don't handle the errors you will get 500 internal server errors and you will not know what's wrong.
Always handle errors.

How can i upload a picture with nodejs and express?

I have a CMS for a food automation system and I'm going to add a part for upload pictures for foods:
<form method="post" enctype="multipart/form-data" action="/upload">
<td><input class="styleFormForAddProducts foodpicForAddFood" type="file" name="file"></td>
<td><input class="styleFormForAddProducts submitForAddFood" type="submit" value="Submit" ></td>
</form>
I wrote this code for making a POST request in Express.js:
app.post('/upload', function (req, res) {
var tempPath = req.files.file.path,
targetPath = path.resolve('./uploads/image.png');
if (path.extname(req.files.file.name).toLowerCase() === '.png') {
fs.rename(tempPath, targetPath, function(err) {
if (err)
throw err;
console.log("Upload completed!");
});
} else {
fs.unlink(tempPath, function () {
if (err)
throw err;
console.error("Only .png files are allowed!");
});
}
});
However when I define this app.use, I get an error:
Middleware: app.use(express.bodyParser({uploadDir:'/img'}));
Error: Error: Most middleware (like bodyParser) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.
When I define a middleware like this :
app.use(bodyParser({uploadDir:'/img/'}));
I don't have any errors but my code doesn't work correctly .
This solution worked for me :
multer = require('multer'),
upload = multer({ dest: 'views/img' });
app.post('/upload',upload.single('file'), function (req, res) {
});
And my form HTML form :
<form method="post" enctype="multipart/form-data" action="/upload">
<input class="styleFormForAddProducts foodpicForAddFood" type="file" name="file">
<input class="styleFormForAddProducts submitForAddFood" type="submit" value="Submit" >
</form>

Uploading multiple files with Multer

I'm trying to upload multiple images using Multer. It all works as expected except that only one file is being uploaded (the last file selected).
HTML
<form class='new-project' action='/projects' method='POST' enctype="multipart/form-data">
<label for='file'>Select your image:</label>
<input type='file' multiple='multiple' accept='image/*' name='uploadedImages' id='file' />
<span class='hint'>Supported files: jpg, jpeg, png.</span>
<button type='submit'>upload</button>
</form>
JS
//Define where project photos will be stored
var storage = multer.diskStorage({
destination: function (request, file, callback) {
callback(null, './public/uploads');
},
filename: function (request, file, callback) {
console.log(file);
callback(null, file.originalname)
}
});
// Function to upload project images
var upload = multer({storage: storage}).any('uploadedImages');
// add new photos to the DB
app.post('/projects', function(req, res){
upload(req, res, function(err){
if(err){
console.log(err);
return;
}
console.log(req.files);
res.end('Your files uploaded.');
console.log('Yep yep!');
});
});
I get the feeling I'm missing something obvious...
EDIT
Code I tried following Syed's help:
HTML
<label for='file'>Select your image:</label>
<input type='file' accept='image/*' name='uploadedImages' multiple/>
<span class='hint'>Supported files: jpg, jpeg, png.</span>
<input type="submit" value="uploading_img">
JS
multer = require('multer'),
var upload = multer();
app.post('/projects', upload.array('uploadedImages', 10), function(req, res, err) {
if (err) {
console.log('error');
console.log(err);
}
var file = req.files;
res.end();
console.log(req.files);
});
Uploading multiple files with Multer
NodeJs Code
Set require files and Storage
const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
const port = 3000
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(__dirname, './images/'))
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + file.originalname.match(/\..*$/)[0])
}
});
Set upload file limit or validataion
const multi_upload = multer({
storage,
limits: { fileSize: 1 * 1024 * 1024 }, // 1MB
fileFilter: (req, file, cb) => {
if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
cb(null, true);
} else {
cb(null, false);
const err = new Error('Only .png, .jpg and .jpeg format allowed!')
err.name = 'ExtensionError'
return cb(err);
}
},
}).array('uploadedImages', 2)
Create the main route for uploading
app.post('/projects', (req, res) => {
multi_upload(req, res, function (err) {
if (err instanceof multer.MulterError) {
// A Multer error occurred when uploading.
res.status(500).send({ error: { message: `Multer uploading error: ${err.message}` } }).end();
return;
} else if (err) {
// An unknown error occurred when uploading.
if (err.name == 'ExtensionError') {
res.status(413).send({ error: { message: err.message } }).end();
} else {
res.status(500).send({ error: { message: `unknown uploading error: ${err.message}` } }).end();
}
return;
}
// Everything went fine.
// show file `req.files`
// show body `req.body`
res.status(200).end('Your files uploaded.');
})
});
Listen port
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
});
HTML code
<form id="form_el" class='new-project' action='/projects' method='POST' enctype="multipart/form-data">
<label for='file'>Select your image:</label>
<input type='file' multiple='multiple' accept='image/*' name='uploadedImages' id='file' />
<span class='hint'>Supported files: jpg, jpeg, png.</span>
<button type='submit'>upload</button>
</form>
JAVASCRIPT CODE
form_el.addEventListener('submit', async function (e) {
const files = e.target.uploadedImages.files;
if (files.length != 0) {
for (const single_file of files) {
data.append('uploadedImages', single_file)
}
}
});
const submit_data_fetch = await fetch('/projects', {
method: 'POST',
body: data
});
Here you go for this example:
var multer = require('multer');
var upload = multer();
router.post('/projects', upload.array('uploadedImages', 10), function(req, res) {
var file = req.files;
res.end();
});
<form action="/projects" method="post" enctype="multipart/form-data">
<input type="file" name="uploadedImages" value="uploading_img" multiple>
<input type="submit" value="uploading_img">
</form>
Visit for more info about Multer.
My guess is that for each file that you want to upload, you reclick:
<input type='file' multiple='multiple' accept='image/*' name='uploadedImages' id='file' />
If you do this, then only the last file selected will be uploaded, as you overwrite the previous selected files.
To upload multiple files, you have to select them all at once in the file picker.

Categories

Resources