How do I upload a file with reactjs without using multipart/form-data? - node.js

I am using Stormpath API and building a web app on top of its React/Express boilerplate. How do I implement without the multipart/form-data option? I've tried using multer but it doesn't work without first specifying the option.
Here's the code snippet for the update profile page. The UserProfilePage component will become a form tag in HTML.
export default class ProfilePage extends React.Component {
constructor(props) {
super(props);
this.state = {resume: 'No Resume Selected'};
this.changeResume = this.changeResume.bind(this);
}
changeResume(e) {
var str = e.target.value;
var n = str.lastIndexOf('\\');
var result = str.substring(n + 1);
this.setState({resume: result});
}
render() {
return (
<DocumentTitle title="Update Profile">
<div className="container">
<div className="row">
<div className="col-xs-12">
<h3>Update Profile</h3>
<hr />
</div>
</div>
<div className="row">
<div className="col-xs-12">
<UserProfileForm>
<div className='sp-update-profile-form'>
<div className="row">
<div className="col-xs-12">
<div className="form-horizontal">
<div className="form-group">
<label htmlFor="givenName"
className="col-xs-12 col-sm-4 control-label">Name</label>
<div className="col-xs-12 col-sm-4">
<input className="form-control" id="givenName" name="givenName" placeholder="Name"
required="true"/>
<input className="form-control" id="surname" name="surname"
style={{display: 'none'}}/>
</div>
</div>
<div className="form-group">
<label htmlFor="email" className="col-xs-12 col-sm-4 control-label">Email</label>
<div className="col-xs-12 col-sm-4">
<input className="form-control" id="email" name="email" placeholder="Email"
required="true"/>
</div>
</div>
<div className="form-group">
<label htmlFor="resume"
className="col-xs-12 col-sm-4 control-label">Resume</label>
<div className="col-xs-12 col-sm-4">
<label className="btn btn-default btn-file">
Browse<input key="resume" id="resume" name="resume"
type="file" style={{display: 'none'}}
onChange={this.changeResume}/>
</label>
<span id="resume_filename"
className="control-label pull-right">{this.state.resume}</span>
</div>
</div>
<div className="form-group">
<label htmlFor="coverletter"
className="col-xs-12 col-sm-4 control-label">Cover
Letter</label>
<div className="col-xs-12 col-sm-4">
<textarea className="form-control" id="coverletter"
name="coverletter" rows="10"/>
</div>
</div>
<div className="form-group">
<div className="col-sm-offset-4 col-sm-4">
<p className="alert alert-danger" spIf="form.error"><span
spBind="form.errorMessage"/></p>
<p className="alert alert-success" spIf="form.successful">
Profile Updated.</p>
<button type="submit" className="btn btn-primary">
Update
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</UserProfileForm>
</div>
</div>
</div>
</DocumentTitle>
);
}

You can try encoding the image using base64 and send it to API as a string.
You can achieve that by using eg. this https://www.npmjs.com/package/base64-img

Related

My Bootstrap form completely disappears due to use of If-else statement with EJS

<div class="row" style="margin: auto; max-width: 850;">
<h1 style="text-align: center">User Registration</h1>
<!-- <div class="well well-sm"><strong><span class="glyphicon glyphicon-asterisk" style="color: red"></span>Required Field</strong></div>-->
<form role="form" action="/users/addUser" method="POST">
<div class="form-group">
<div class="span6">
<div class="col-lg-4">
<div class="form-group">
<label for="InputEmail">Username</label>
<div class="input-group">
<input type="text" style="width: 180%" class="form-control" id="username" name="username" placeholder="username" required>
<!--
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
-->
</div>
</div>
</div>
</div>
<div class="span6">
<div class="col-lg-4">
<div class="form-group">
<label for="InputEmail">Password</label>
<div class="input-group">
<input type="password" style="width: 180%" class="form-control" id="password" name="password" placeholder="password" required>
<!--
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
-->
</div>
</div>
</div>
</div>
<!--
<div class="form-group">
<label for="InputMessage">Enter Message</label>
<div class="input-group">
<textarea name="InputMessage" id="InputMessage" class="form-control" rows="5" required></textarea>
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
</div>
</div>
<input type="submit" name="submit" id="submit" value="Submit" class="btn btn-info float-xs-right">-->
<div class="col-lg-5 push-md-1">
<div class="col-md-12">
<% if(isRegistered) { %>
<div class="alert alert-success">
<strong><span class="glyphicon glyphicon-ok"></span> <%= msg %>.</strong>
</div>
<% } else { %>
<div class="alert alert-danger">
<span class="glyphicon glyphicon-remove"></span><strong> <%= msg %> </strong>
</div>
<% } %>
</div>
</div>
<br>
<br>
<br>
<hr>
<input type="submit" name="submit" id="submit" value="Submit" class="btn btn-info float-xs-right">
</form>
</div>
As shown above, if i use "If-else " statement with EJS, my form disappears and if i remove it, my form appears on the browser again.
What i'm trying is to have a registration page where if the user already exists, an alert message to be displayed on the corner side of the browser saying, 'user already exists'. By the way this alert message is coming from my db (Oracle 11g).

Angular 4 email Contact form

I'm pretty new to Angular and have been tasked to complete a "Contact Us" form to allow customers to send emails through the web form.
The HTML:
<div class="content-section">
<div class="container">
<div class="row">
<div class="">
<h2 class="intro-title">Contact Us</h2>
<form class="well form-horizontal" action=" " method="post" id="contact_form">
<div class="col-lg-6 spacer">
<div class="fadeIn-1">
<p>
<strong>Contact us</strong>
<br />
111.222.3333
<br />
information#mysite.com
</p>
</div>
<br />
<div class="fadeIn-2">
<p>
<strong>Office 1</strong>
<br />
Our street address
<br />
City, state, zip
</p>
</div>
<br />
<div class="fadeIn-3">
<p>
<strong>Office 2</strong>
<br />
street address
<br />
City, state, zip
</p>
</div>
</div>
<fieldset>
<!-- Form Name -->
<legend>Send us a message</legend>
<!-- Text input-->
<div class="form-group">
<!--<label class="col-md-4 control-label">First Name</label>-->
<div class="col-md-6 inputGroupContainer">
<div class="input-group animated-delay-1">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input name="name" placeholder="Name" class="form-control" type="text">
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<!--<label class="col-md-4 control-label">E-Mail</label>-->
<div class="col-md-6 inputGroupContainer">
<div class="input-group animated-delay-2">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input name="email" placeholder="E-Mail Address" class="form-control" type="text">
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<!--<label class="col-md-4 control-label">Phone #</label>-->
<div class="col-md-6 inputGroupContainer">
<div class="input-group animated-delay-3">
<span class="input-group-addon"><i class="glyphicon glyphicon-earphone"></i></span>
<input name="phone" placeholder="(801)222-3333" class="form-control" type="text">
</div>
</div>
</div>
<div class="form-group">
<!--<label class="col-md-4 control-label">Subject</label>-->
<div class="col-md-6 inputGroupContainer">
<div class="input-group animated-delay-4">
<span class="input-group-addon"><i class="glyphicon glyphicon-bookmark"></i></span>
<input name="subject" placeholder="Subject" class="form-control" type="text">
</div>
</div>
</div>
<div class="form-group">
<!--<label class="col-md-4 control-label">Message</label>-->
<div class="col-md-6 inputGroupContainer">
<div class="input-group animated-delay-5">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
<textarea rows="9" class="form-control" name="comment" placeholder="Message">
</textarea>
</div>
</div>
</div>
<!-- Button -->
<div class="form-group">
<div class="col-md-4">
<button type="submit" class="btn btn-primary">Send
<span class="glyphicon glyphicon-send"></span>
</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
This is this the component:
import { Component } from '#angular/core';
import { trigger, state, style, transition, animate } from '#angular/animations';
import { slideInOutAnimation, fadeInAnimation } from '../_animations/index';
#Component({
selector: 'contact-page',
templateUrl: './contact.component.html',
styleUrls: ['./contact.component.css'],
animations: [slideInOutAnimation, fadeInAnimation, trigger('slideInOut', [
state('in', style({
transform: 'translate3d(0, 0, 0)'
})),
state('out', style({
transform: 'translate3d(100%, 0, 0)'
})),
transition('in => out', animate('400ms ease-in-out')),
transition('out => in', animate('400ms ease-in-out'))
]),
],
host: {
'(window:scroll)': 'updateHeader($event)',
'[#slideInOutAnimation]': '',
'[#fadeInAnimation]': ''
}
})
export class ContactComponent {
title = 'app';
isScrolled = false;
currPos: Number = 0;
startPos: Number = 0;
changePos: Number = 0;
menuState = 'out';
constructor() { }
updateHeader(evt) {
this.currPos = (window.pageYOffset || evt.target.scrollTop) - (evt.target.clientTop || 0);
if (this.currPos >= this.changePos) {
this.isScrolled = true;
} else {
this.isScrolled = false;
}
}
}
I've looked at options such as "nodemailer" and I just can't seem to figure out how it all works.
I need the email to be sent to our email address when a customer clicks the submit button. Any suggestions?
Also, I'm not really sure what else is needed to get help, so if you need anything else, I am happy to post it up.

SailsJS : Mysterious null values

my problem is that whenever a new client is created, all the values are null in the database except the id, the name, responsable and the logo. i dont think i did a programmation mistake, so i think it is a case of callbacks race but i cant found the solution.
P.S : the problem occure only if i select and send an image file to be uploaded, in the other case, the client values are stored correctly.
P.S 2 : the problem occure in my remote server only, in local environnement all is ok !
Than you very much !
UPDATE : i included the code for my create.ejs view
This is the code of the store method in my ClientService :
store: function(req, done) {
var name = req.param('name'),
town = req.param('town'),
adress = req.param('adress'),
postalCode = req.param('postalCode'),
telephone = req.param('telephone'),
email = req.param('email'),
fax = req.param('fax'),
responsable = req.param('responsable'),
website = req.param('website'),
activity = req.param('activity');
comments = req.param('comments');
Client.create({
name: name,
town: town,
adress: adress,
postalCode: postalCode,
telephone: telephone,
fax: fax,
responsable: responsable,
website: website,
activity: activity,
email: email,
comments: comments
}).exec(function(err, client) {
if (err) console.log(err);
req.file('logo').upload(
{
dirname: sails.config.appPath + sails.config.params.logos
},
function(err, logo) {
if (err) return done(err, null);
if (logo.length !== 0) {
client.logo = require('path').basename(logo[0].fd);
} else {
client.logo = 'default.png';
}
client.save(function(err) {
return done(null, client);
});
}
);
});
}
And this is the code for the EJS view :
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="store" method="POST" class="form-horizontal" enctype="multipart/form-data">
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group form-md-line-input has-success form-md-floating-label form-create">
<div class="input-icon">
<input type="text" class="form-control" name="name">
<label for="form_control_1">Nom du Client</label>
<i class="fa fa-institution"></i>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group form-md-line-input has-success form-md-floating-label form-create">
<div class="input-icon">
<input type="text" class="form-control" name="activity">
<label for="form_control_1">Activité</label>
<i class="icon-star"></i>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group form-md-line-input has-success form-md-floating-label form-create">
<div class="input-icon">
<input type="text" class="form-control" name="responsable">
<label for="form_control_1">Responsable</label>
<i class="icon-user"></i>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group" style="margin-left:15px;">
<div class="form-photo-label-form" >
<i class="icon-picture icon-create"></i>
<label for="form_control_1" class="form-photo-create" >Photo </label>
</div>
<br>
<div class="fileinput fileinput-new" data-provides="fileinput">
<span class="btn green btn-file">
<span class="fileinput-new"> Selectionner Fichier </span>
<span class="fileinput-exists"> Changer </span>
<input type="file" name="logo"> </span>
<span class="fileinput-filename"> </span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group form-md-line-input has-success form-md-floating-label form-create">
<div class="input-icon">
<input type="text" class="form-control" name="email">
<label for="form_control_1">Email</label>
<i class="fa fa-inbox"></i>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group form-md-line-input has-success form-md-floating-label form-create">
<div class="input-icon">
<input type="text" class="form-control" name="adress">
<label for="form_control_1">Adresse</label>
<i class="icon-home"></i>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group form-md-line-input has-success form-md-floating-label form-create">
<div class="input-icon">
<input type="text" class="form-control" name="postalCode">
<label for="form_control_1">Code postale</label>
<i class="fa fa-send"></i>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group form-md-line-input has-success form-md-floating-label form-create">
<div class="input-icon">
<input type="text" class="form-control" name="town">
<label for="form_control_1">Ville</label>
<i class=" fa fa-map"></i>
</div>
</div>
</div>
<!--/span-->
</div>
<div class="row">
<div class="col-md-6">
<div class="row">
<div class="col-md-12">
<div class="form-group form-md-line-input has-success form-md-floating-label form-create">
<div class="input-icon">
<textarea class="form-control" rows="3" style="height: 192px; resize:none " name="comments"></textarea>
<label for="form_control_1">Commentaire</label>
<i class=" fa fa-edit"></i>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="row">
<div class="col-md-12">
<div class="form-group form-md-line-input has-success form-md-floating-label form-create">
<div class="input-icon">
<input type="text" class="form-control" name="telephone">
<label for="form_control_1">Telephone</label>
<i class="icon-screen-smartphone"></i>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group form-md-line-input has-success form-md-floating-label form-create">
<div class="input-icon">
<input type="text" class="form-control" name="fax">
<label for="form_control_1">Fax</label>
<i class="fa fa-fax"></i>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group form-md-line-input has-success form-md-floating-label form-create">
<div class="input-icon">
<input type="text" class="form-control" name="website">
<label for="form_control_1">Site Internet</label>
<i class=" fa fa-internet-explorer"></i>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="form-actions right">
<button type="button" class="btn default">Annuler</button>
<button type="submit" class="btn green"><i class="fa fa-check"></i> Enregistrer</button>
</div>
</form>
Nothing mysterious (:
Your problem is that You use req.param instead of req.body
And Your code is simply should look like this:
const path = require('path'); // somewhere in same module at the top
store: (req, done) => {
Client
.create(req.body)
.exec((err, client) => {
if(err) {
// no need to go further
// if You cannot create database record
return done(err);
}
const dirname = path.join(sails.config.appPath, sails.config.params.logos); // safely concatenates paths based on OS
req
.file('logo')
.upload({dirname}, (err, logo) => {
if (err) {
// we created record (client)
// but could not save the file
// it should not be a stopper
console.error(err);
}
client.logo = (logo) ? path.basename(logo[0].fd) : 'default.png';
client.save((err) => {
if(err) {
// just log the error and continue
console.error(err);
}
done(null, client);
});
});
});
}
P.S. When You pass req.body (or any other) object to Client.create don't worry about object contents, just define field constrains in You model file, ODM (or ORM) will just handle validation automatically based on constraints and will prevent from creating null valued fields
Example:
module.exports = {
attributes: {
name: {
// it requires field name:
// to be defined (required: true),
// to be string (type),
// to have at least 2 symbols,
// to not exceed 100 symbols
type: 'string',
required: true,
minLength: 2,
maxLength: 100
},
email: {
// it requires field email:
// to be defined (required: true),
// to be email (type),
// to be unique among documents, records, rows
type: 'email',
required: true,
unique: true
},
... and so on ...
}
}
More about validation here
Thanks everybody. I solved the problem by putting the file input at the end the form. Like you suggested, the values after the file input were reset after the upload of the file

Express fails to find resources in case of parameterized route. What am I missing?

In my express app I have a separate file for middlewares. I used express.static to make the resources available to the app. Code from middlewares.js...
app.use(express.static('public'));
app.use(express.static('node_modules/vue/dist'));
app.use(express.static('node_modules/bootstrap/dist/css'));
app.use(express.static('node_modules/bootstrap/dist/js'));
app.use(express.static('node_modules/multiple.js'));
app.use(express.static('node_modules/chart.js/dist'));
It works fine for all the routes. However, when I try to define a parameterized route, and render a template this way, it fails to load up the resources. Express fails to find CSS/JS/Image files from those statics. What am I missing here? Here is my code for the route..
app.get('/invoices/:id', app.authenticated, (req, res) => {
Invoices.find({_id: req.params.id}, (err, invoice) => {
if (err) {
res.json({error: err});
}
res.render('invoicesCreate');
});
});
Updated: The View file
{{#section 'classes'}}has-navigation page-dashboard{{/section}}
{{#section 'body-classes'}}-fluid{{/section}}
<div class="row" id="invoicer">
<div class="col-xs-12 col-md-6">
Fill your details and get live preview in the right side
<form class="" action="/invoices" method="post" enctype="multipart/form-data">
<div class="">
<div class="invoiceform-logo-container">
<input type="file" name="profilelogo" id="fileinput" accept="image/*" v-on:change="updateImage()">
<img v-bind:src="logo" alt="" />
</div>
<div class="invoiceform-number"></div>
<div class="invoiceform-currency"></div>
</div>
<div class="divider"></div>
<div class="">
Your Name / Company Name
<textarea name="company_name" rows="8" cols="40" v-model="from"></textarea>
Client Name / Company Name
<textarea name="client_name" rows="8" cols="40" v-model="to"></textarea>
\{{date_title}}
<input type="date" name="start_date" v-model="date">
\{{due_date_title}}
<input type="date" name="end_date" v-model="due_date" v-bind:min="date">
\{{balance_title}} \{{balance}}
<div class="input-group">
<span class="input-group-addon">$</span>
<input name="end_date" type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">
</div>
</div>
<div class="invoiceform-itemlist" v-on:focusout="checkToRemove()">
<div class="">
\{{item_header}}
\{{quantity_header}}
\{{unit_cost_header}}
\{{amount_header}}
</div>
<div class="" v-for="item in items">
<input type="text" name="items[1][item_name]" v-model="item.head">
<input type="number" name="items[1][item_quantity]" v-model="item.quantity" min="0" v-on:blur="updateAmount($index)">
<input type="number" name="items[1][item_rate]" v-model="item.rate" min="0" v-on:blur="updateAmount($index)">
<input type="number" name="items[1][item_amount]" v-model="item.amount">
</div>
<button type="button" name="button">Add Item</button>
</div>
<div class="divider"></div>
<div class="">
\{{subtotal_title}} \{{subtotal}}
\{{tax_title}}
<div class="input-group">
<input type="text" class="form-control" aria-label="Text input with dropdown button" v-model="tax">
<span class="input-group-addon">
<input type="radio" name="" aria-label="Checkbox for following text input"> %
</span>
<span class="input-group-addon">
<input type="radio" name="" aria-label="Checkbox for following text input"> F
</span>
</div>
<div id="discount" v-if="fields.discount">
Discount <input type="number" name="" v-model="discounts">
</div>
<div id="shipping" v-if="fields.shipping">
Shipping <input type="number" name="shipping" v-model="shipping">
</div>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary">
<input type="checkbox" name="discount" v-model="fields.discount"> \{{discounts_title}}
</label>
<label class="btn btn-primary">
<input type="checkbox" name="shipping" v-model="fields.shipping"> \{{shipping_title}}
</label>
</div>
</div>
<div class="divider"></div>
<div class="">
Total <input type="number" name="name" v-model="total" min="0">
\{{amount_paid_title}} <input type="number" name="total" v-model="amount_paid" min="0" v-bind:max="total">
</div>
<div class="divider"></div>
<div class="">
\{{notes_title}}
<input type="text" name="name" v-model="notes">
\{{payment_terms_title}}
<input type="text" name="name" v-model="terms">
<button type="submit" name="button">Save Now</button>
<button type="button" name="button">Download PDF</button>
</div>
</form>
</div>
<div class="col-xs-12 col-md-6 hidden-sm-down"></div>
</div>
{{#section 'script'}}
window.invoice = {{{json defaultInvoice}}}
console.log({{{json defaultInvoice}}})
{{/section}}

Unable to post from bootstrap modal

In the header of my app, I have a link, clicking on which opens up the bootstrap popup modal. When I insert data in the text boxes and click on Submit, No action is happening. Please advice. Thanks.
Here is my html for the modal:
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal title</h4>
</div>
<form action="addCard" method="post" id="addcard" class="form-horizontal" role="form">
<div class="modal-body" style="height: 140px;">
<div class="form-group" style="height: 30px;">
<label for="title" class="col-md-3 control-label">Title</label>
<div class="col-md-9">
<input type="text" class="form-control" name="title" placeholder="Enter Card title here...">
</div>
</div>
<div class="form-group" style="height: 30px;">
<label for="title" class="col-md-3 control-label">Description</label>
<div class="col-md-9">
<input type="text" class="form-control" name="desc" placeholder="Enter Card description here...">
</div>
</div>
<div class="form-group">
<label for="priority" class="col-md-3 control-label">Priority</label>
<div class="col-md-9">
<select name="priority" class="form-control">
<option value="critical">Critical</option>
<option value="high">High</option>
<option value="normal">Normal</option>
<option value="low">Low</option>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" type="submit">Submit</button>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
I have this line in my app.js file:
app.post('/addCard', routes.addCard);
Index.js:
exports.addCard = function (req,res)
{
res.render('index');
}

Resources