How to upload a file to Parse.com using simple HTML form? - node.js

I want to upload a simple image file along with text value to a Parse.com project at www.willubmy.com/create. But either I am not getting the correct enctype or Parse's node requires some changes. Can you please help resolve this issue? I am getting the POST variables normally but am not able to get anything when I send a file along
Simplified HTML
<form>
Question:<br>
<input type="text" name="questionString">
<br>
username:<br>
<input type="text" name="username">
<input type="file" name="file">
</form>
My Cloud Code
app.post('/create', function(req, res) {
var username = req.body.username;
var questionString = req.body.questionString;
var positiveAnswer = req.body.positiveAnswer;
var negativeAnswer = req.body.negativeAnswer;
var email = req.body.email;
console.log(username + questionString + positiveAnswer + negativeAnswer + email + JSON.stringify(req.body));
console.log("req files : " + req.files);

This documentation can help you:
https://www.parse.com/questions/uploading-files-to-parse-using-javascript-and-the-rest-api

Related

what is use of router and model in loopback

hello guys i m new to loopback so can anyone help me with this basic. i had created a some code but don't know how this flow (from route to model)
here is route.js code for login
var path = require('path');
module.exports = function(app) {
app.get('/', function(req, res) {
res.render('login');
});
app.post('/login', function(req, res) {
//from here i should go to login model
});
};
here is my login.ejs
<form action="/login" method="post">
<input type="text" name="username" placeholder="username">
<input type="password" name="password" placeholder="password">
<input type="submit" name="" value="Submit">
</form>
now my question is that how i can use login model from route.js (url is like "login") i know i can use this type as describe below in route.js but i want that first it go to router and from then i go to login model more description eg it go through "/login" route from there it go to login model where i want to add insert login after that if it response success then it go to "/home" else it go to "/"
"var User = app.models.user;"
i what something like this in user.js (model)
module.exports = function(User) {
//here i want to accept login form method and insert it into dataabase
};
or this is not possible or it is incorrect way i don't know much so please help
what is different between if i use business login in router and model i m new so please help.
First go to the loopBack documentation and read it carefully how to create models and its control flow , surely you will get clear picture
https://loopback.io/doc/en/lb2/Project-layout-reference.html

Extracting uploaded csv data with multer

I am porting a rails app over to use the MEEN stack (Mongo, Express, Ember, Node)
I have a function that takes an uploaded csv and extracts the data from it and uses the data to then form SQL queries to a database. For some reason I am having issues with accessing the uploaded csv data with multer.
My Router file
var quotes = require('../api/quote');
var cors = require('cors');
var sku = require('../api/tools/sku');
var multer = require('multer');
var upload = multer({ dest: 'uploads/' });
var util = require("util");
var fs = require("fs");
var corsOptions = {
origin: 'http://localhost:4200'
}
module.exports = function(router){
router.route('/quotes').post(cors(corsOptions),function(req,res){
console.log(req.body);
quotes.addQuote(req,res);
}).get(cors(corsOptions),function(req,res){
quotes.getAllQuotes(req,res);
});
router.route('*').get(cors(corsOptions), function(req,res){
res.sendFile('public/index.html',{root:'./'});
});
router.post('/tools/sku/reactivate',upload.single('csvdata'),function(req,res){
console.log(req.files);
console.log('handing request over to sku.reactivate');
sku.reactivate(req,res);
});
};
My handlebars file for the tools/sku/reactivate template
<div class="col-md-8 col-md-offset-2 text-center">
<h2 class="toolTitle">Reactivate SKUs</h2>
<p class="lead">CSV Should Contain 1 Column (SKU) Only</p>
{{file-upload enctype="multipart/form-data" type="file" url="/tools/sku/reactivate" class="center-block" accept="text/csv" name="csvdata"}}
</div>
i am getting Error: Unexpected field when I attempt to post the file upload to the /tools/sku/reactivate post route. I don't understand whats wrong with my code.
The issue was using the file-upload ember addon. As soon as I removed the handlebars component and just hardcoded a form as seen below, the file upload's successfully.
<div class="col-md-8 col-md-offset-2 text-center">
<h2 class="toolTitle">Reactivate SKUs</h2>
<p class="lead">CSV Should Contain 1 Column (SKU) Only</p>
<form action="/tools/sku/reactivate" method="POST" enctype="multipart/form-data">
<input class="center-block" type="file" name="csvdata">
<button type="submit" class="btn btn-md btn-danger">Submit</button>
</form>
</div>

Req.file object is always undefined, HTTP file upload

I'm trying to upload a file in meteor using HTTP POST method and enctype="multipart/form-data"
WebApp.connectHandlers.use("/api/v1/upload", function(req, res, next) {
console.log(req.files); //undefined
console.log(req.file); //undefined
console.log(req);
})
I tried with WebApp but getting undefined file property under request object
I also tried with multer and Picker but no luck.
const _multerInstanceConfig = { dest: '/tmp' }; // Temp dir for multer
const _multerInstance = multer(_multerInstanceConfig);
Picker.middleware(_multerInstance.single('photo'));
Picker.route('/api/v1/upload', function(params, req, res, next) {
console.log(req.files); //undefined
console.log(req.file); //undefined
console.log(req);
})
This is simplest form I'm trying to upload is
<form action="http://localhost:3000/api/v1/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload File" />
</form>
Am I missing something here? not sure.
Also, I don't want to upload files using base64 data string via DDP as it very slow.
I've check couple of link also with no luck
multer - req.file always undefined
https://github.com/noris666/Meteor-Files-POST-Example
PS: I need to upload images via native Android/iOS clients.
Thanks, everyone, who has spent their time on my question, I got the solution for the problem from git issue, I raised.
I'm posting here my solution if someone else also faces the similar problem.
It was because of the name of this input field
<input type="file" name="file" />
which doesn't match with
Picker.middleware(_multerInstance.single('photo'));
changing either of them to will make it work perfectly.

What am i missing for the file upload using multipart form data ?

Hi for whatever reason i cannot use packages e.g. multer to upload file to node server. So i found example online, if just upload file in the form, it works fine.
Now i want to send another field "password" together with the file during submit, just cannot make it a work.
I do know there're plenty modules out there, for now just want to this example to work.
<form style="height: 100%;padding-bottom:63px;">
<p>
<input type="file" class="FirmwareFile"
name="myUpload" file-model="upload.newFwFile">
</p>
<p>
<input type="password" name="password" id="password"
placeholder="Password"
ng-model="upload.controllerPassword"
class="formInput">
</p>
</form>
httpSvc.uploadToUrl(myFile, myPd, myServerIPAddress, myRoute) {...}
factory.uploadToUrl = function (fwFile, pd, myServerIp, myRoute) {
var fd = new FormData();
//fd.append('passwd', pd); // cannot pass password to server side ?
fd.append('file', fwFile); // only this works
var deferred = $q.defer();
var completeUrl = ......
$http.post(completeUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function (data) {
deferred.resolve(data);
}).error(function () {
deferred.reject();
});
return deferred.promise;
}
in server side, where to extract the password info please ?
var UploadImage = function(req, res, callback){
var destFile = fs.createWriteStream(uploadDest + "mytest");
var fileSize = req.headers['content-length'];
req.pipe(destFile); //why not sth. like req.body.file.pipe() ?
...
};
Your form does not have
<form enctype="multipart/form-data" action="..." method="...">
...
</form>
You will be better off using node-formidable. The example works straight out of the box. You might also want to look into angularJS specific form upload directives that have been made. No sense in reinventing the wheel.
Cheers

Accessing parameters from nodeJS/ExpressJS sent from html form by POST Method

I would like to know the command to access parameters sent through post method from HTML Forms
I have tried all these but they print undefined or sends back an error ...
EDIT 1: Forgot to mention, I have also added this server.use(express.bodyParser());
EDIT 2:
var express = require('express'),
server = express(),
client = require('mysql').createConnection({ host:'localhost', user:'root', password:'password' });
using dbCRUD for rest services in MySQL
var dbcrud = require('dbcrud').init(client, 'contacts', model);
then I do a
server.use(express.bodyParser());
the post functionality is carried out here..
server.post('/families',function(req,res){
console.log(req.id);
console.log("1: " + req.param.id);
console.log("2: " + req.params.id);
console.log("3: " + req.param("id"));
console.log("4: " + req.params('id'));
console.log("5: " + req.params[0]);
console.log("6: " + req.body.name);
console.log("7: " + req.body.notes);
console.log("8: " + req.body.id);
//console.log("5: " + req.params[0]);
res.send('Hello POST : families');
});
I add the routes here...
dbcrud.addRoutes(server);
In HTML Form i have specified the id and name attributes for the input tag ...
<form method="post" action="http://10.180.218.72:3000/families">
id : <input type="number" id="id" name="id"></input>
name : <input type="text" id="name" name="name"></input>
notes : <input type="text" id="notes" name="notes"></input>
<input type="submit" value = "submit" ></input>
</form>
Try app.use(express.bodyParser()); in your code. bodyParser is a express middleware for parsing body of post request.

Resources