Upload a file with ServiceStack ss-utils.js - servicestack

I have a job application form as part of a site built on ServiceStack. I am attempting to use the included ss-utils.js to leverage built-in Fluent Validation, but my form doesn't post the user's file upload. Here's the relevant snippet of the form:
<form id="form-careerapplication" action="#(new CreateCareerApplication().ToPostUrl())" method="post">
<div class="error-summary"></div>
<div class="form-group">
<label>
Upload Resume
</label>
<input type="file" id="Resume" name="Resume" />
<span class="help-block"></span>
</div>
<input type="hidden" name="Id" value="#Model.Id" />
<input type="submit" value="Submit Application" />
</form>
<div id="success" class="hidden">
Thank you for your application.
</div>
$("#form-careerapplication").bindForm({
success: function (careerApplicationResponse) {
$("#form-careerapplication").addClass("hidden");
$("#success").removeClass("hidden");
},
...
Is there something I'm missing in ss-utils.js? Or is there a way of overriding / supplementing the submit behavior to use FormData?

Uploading files via a HTML FORM requires a enctype="multipart/form-data", e.g:
<form id="form-careerapplication" action="#(new CreateCareerApplication().ToPostUrl())"
method="post" enctype="multipart/form-data">
...
</form>
If you want to change support multiple file uploads or change the appearance of the UI Form I recommend the Fine Uploader, there's an example showing how to use Fine Uploader on the HTTP Benchmarks Example.
Whilst Imgur has a simple client HTML and Server example.

Turned out I can use the beforeSend option as part of the configuration passed into bindForm to override the data being sent. Its a bit of a hack, but it worked and I keep the original ss-utils.js fluent validation!
$("#form-careerapplication").bindForm({
success: function (careerApplicationResponse) {
....
},
error: function (error) {
....
},
contentType: false,
processData: false,
beforeSend: function (x, settings) {
var fd = new FormData();
// Tweaked library from https://github.com/kflorence/jquery-deserialize/blob/master/src/jquery.deserialize.js
// Used to translate the serialized form data back into
// key-value pairs acceptable by `FormData`
var data = $.fn.deserialize(settings.data);
$.each(data, function (i, item) {
fd.append(item.name, item.value);
});
var files = $('#form-careerapplication').find("input:file");
$.each(files, function (i, file) {
fd.append('file', file.files[0], file.files[0].name);
});
settings.data = fd;
}
});

Related

Post image file using axios in react app sending strange data to backend

I'm currently trying to post a photo file upload to my backend, to be stored in the file system. However, whenever I do, it produces an absolutely bizarre string of numbers / letters when I console log the req.body.
I've no idea what this is, why it's happening or how to convert it into the image I need to store in my file system.
Here's my uploadPhoto and buttonClick (aka submit) functions:
const uploadPhoto = (e) => {
e.preventDefault()
setPreviewPhoto(URL.createObjectURL(e.target.files[0]))
setPhotoFile(e.target.files[0])
}
const buttonClick = async (e) => {
e.preventDefault()
const formData = new FormData()
formData.append('photoFile', photoFile)
await axios.post("/api/uploadProfilePicture", formData, { headers: { 'content-type': 'multipart/form-data' }}, { transformRequest: formData => formData })
}
And here's my form that's used to upload the image:
<form className="setup-form" method="POST" encType="multipart/form-data" onSubmit={buttonClick}>
<label className="setup-label">Your name</label>
<input className="setup-input" type="text" name="name" onChange={onChange} value={name} />
<label className="setup-label">Your photo</label>
<div className="setup-photo-hint-container">
<div className="setup-photo-div">
<label for="photoFile" className="setup-photo-label">Upload</label>
<input className="setup-photo-input" id="photoFile" type="file" onChange={uploadPhoto} name="photoFile" />
</div>
</div>
</form>
Does anyone have any idea what I'm doing wrong here? I don't understand why it's going to the request body for one, or why it's producing these characters for another.

how make checkbox stay checked and reset in node js

I am working on a small project with checkbox and node js. I need the checked box stay on the screen after I click submit button and reset the form after clicking reset button.How can do that?
ejs code
<form method="post" action="/">
<input type="checkbox" name="preference" value="A">A
<input type="checkbox" name="preference" value="B">B
<input type="checkbox" name="preference" value="C">C
<input type="submit" value="Click to Submit">
<input type="reset" value="Erase and Restart">
</form>
node js
express.get('/', (req, res) => {
res.render('form');
});
express.post('/', (req, res) => {
console.log(req.body);
let checkedValue =req.body.preference;
let output = checkedValue==undefined?`You didn' make selection.`:`The preference iterm on menu is ${checkedValue}`;
res.render('form',{
output:output,
});
});
What's going on is that when you submit your form, the webpage is reloaded, so you lose your checked state. You can either save the values on your server and have them pre-checked using an optional checked flag in your ejs template or you can add some client side javascript to handle the form submission for you by writing and event handler for the submit event on the form.
if you expand your ejs template with a conditional checked value on your inputs, your returned page will have them pre-checked
<input type="checkbox" name="preference" <% if (submittedValue === "A") { %>checked<% } %> value="A">A
Or, here's a super simple bit of javascript that would send the values to your server
document.forms[0].addEventListener('submit', function (e) {
e.preventDefault(); // prevent the form from submitting with a page refresh
const data = { values: [] };
e.target.elements.forEach((formEl) => {
if (formEl.checked) data.values.push(formEl.value);
});
fetch('/urlToProcessYourForm', { method: 'POST', body: JSON.stringify(data) });
});

Upload image to database using angular

I got stuck while uploading updating user avatar on my website. I'm using angular and need to upload image using form and get base64 encoding of this image to pass as a parameter into my backend.
onUploadFinished(event){
const avatar ={
avatar:event.file
}
console.log(avatar)
//validate avatar
if(!this.validateService.validateAvatarUpdate(avatar.avatar)){
this.flashMessage.show('Please, select a new avatar', {cssClass: 'alert-danger', timeout:3000});
return false;
}
this.updateService.updateAvatar(avatar).subscribe(data=>{
console.log()
if(data/*.success*/){ //commented cause response doesnt have property success but still registering user without displaying the flash message
this.flashMessage.show('You successfuly changed your avatar', {cssClass: 'alert-success', timeout:3000});
this.router.navigate(['/profile'])
this.authService.getProfile().subscribe(profile=>{
this.user = profile.user;
},
err=>{
console.log(err);
return false;
});
}else{
this.flashMessage.show('Something went wrong', {cssClass: 'alert-danger', timeout:3000});
this.router.navigate(['/profile'])
}
});
}
I was trying to use ng2-image-upload here is html
<h6>Upload new photo...</h6>
<!-- <form (submit)="onUserAvatarSubmit()" enctype="multipart/form-data">
<input type="file" name="avatar" class="text-center center-block well well-sm">
<p></p>
<input class="btn btn-primary" value="Upload" type="submit">
</form> -->
<image-upload name="avatar" [class]="'customClass'"
[headers]="{Authorization: this.authToken}"
[buttonCaption]="'Choose an Image'"
[dropBoxMessage]="'or just drop them here'"
(uploadFinished)="onUploadFinished($event)"
[url]="''">
</image-upload>
Maybe anyone had such experience with uploading images, so give me some tips how to deal with it. Thanks here is a screenshot So you see when displaying this image we can see its base64 but I cant take it.

NodeJS Post request using a Button

I don't know if this is possible or not. All the research I've done has shown that it is possible with a form and text input. But anyways, Using NodeJs & Express I want to be able to click a button on my webpage, and once it's clicked, it sends a post request to my Node.JS server.
Simpler way of saying it:
When button is clicked, send info to the server.
Goal I'm trying to achieve:
When button is clicked, it sends some sort of ID/code/anything to turn on a service from my database. (I have yet to learn how db's work so I am just trying to focus on front end.)
Code I have so far:
app.post("/send", function(req, res){
var newID = req.body.ID;
res.redirect("/action")
});
<form action="/send" method="POST">
<input type="button" name="newID" placeholder="Button">
<button>send</button>
</form>
You do not need to use jQuery or AJAX.
Simply add an input of type submit inside the form tag so that the POST request defined by your form tag is submitted.
Your newID input should be of type text, this allows entering a value in the input field.
The newID value can be retrieved server side with req.body.newID (be sure to use the body-parser middleware).
<form action="/send" method="POST">
<input type="text" name="newID" placeholder="Enter your ID"/>
<input type="submit" value="Click here to submit the form"/>
</form>
For this purposes you should use $.ajax,
example:
$('button').on('click', function() {
$.ajax({
type: 'POST',
url: '/send',
data: { ID: 'someid' },
success: function(resultData) {
alert(resultData);
}
});
});

meteor-typeahead: Listing and selecting

I have installed meteor-typeahead via npm. https://www.npmjs.org/package/meteor-typeahead
I have also installed
meteor add sergeyt:typeahead
from https://atmospherejs.com/sergeyt/typeahead
I am trying to get the data-source attribute example to function so I can display a list of countries when the user begins to type. I have inserted all countries into the collection :-
Country = new Meteor.Collection('country');
The collection is published and subscribed.
When I type into the input field, no suggestions appear. Is it something to do with activating the API? if so how do I do this? Please reference the website https://www.npmjs.org/package/meteor-typeahead
My form looks like this:
<template name="createpost">
<form class="form-horizontal" role="form" id="createpost">
<input class="form-control typeahead" name="country" type="text" placeholder="Country" autocomplete="off" spellcheck="off" data-source="country"/>
<input type="submit" value="post">
</form>
</template>
client.js
Template.createpost.helpers({
country: function(){
return Country.find().fetch().map(function(it){ return it.name; });
} });
In order to make your input to have typeahead completion you need:
Activate typeahead jQuery plugin using package API
Meteor.typeahead call in template rendered event handler.
Meteor.typeahead.inject call to activate typeahead plugin for elementes matched by CSS selector available on the page (see demo app).
Write 'data-source' function in your template understandable by typeahead plugin. It seems your 'data-source' function is correct.
Add CSS styles for typeahead input(s)/dropdown to your application. See example here in demo app.
Try this way in your template:
<input type="text" name="country" data-source="country"
data-template="country" data-value-key="name" data-select="selected">
Create template like country.html (for example /client/templates/country.html) which contains:
<template name="country">
<p>{{name}}</p>
</template>
In your client javascript:
Template.createpost.rendered = function() {
Meteor.typeahead.inject();
}
and
Template.createpost.helpers({
country: function() {
return Country.find().fetch().map(function(it){
return {name: it.name};
});
},
selected: function(event, suggestion, datasetName) {
console.log(suggestion); //or anything what you want after selection
}
})

Resources