app.post('/addimage', upload.single('image'), function(request, response){
console.log(request.body)
const body = request.file
console.log(body)
response.redirect('/image')
})
var storage = multer.memoryStorage()
var upload = multer({ storage: storage })
<div class="form-group">
<label for="image">Choose a image</label>
<input type="file" class="form-control-file" id="image" name="image">
</div>
First is the nodejs code and second part is the html form. The request.body returns the image file name but when i do the request.file(s) its just undefined. Ive tried
Solved needed to add enctype="multipart/form-data" in the form. Should have posted the full form for better help. Sorry
Related
I wanted to create a save feature for my flashcard app. The solution I thought of first would be to save details about every card added, so on start the app could retrieve all of that data and format the flashcards the way you left them. I set up a node express js server, but when I post from the form, the page goes blank. However, the data is posted which I just have console logging to the node server. How can I make the page not go blank and just stay on index html and function normally?
NodeJS Server:
const bodyParser = require("body-parser");
const fs = require("fs")
const app = express();
let urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(express.json());
app.use(express.static("public"));
app.listen(3000, () => {
console.log("Server Started");
})
app.post("/", urlencodedParser, (req, res) => {
//add data to json
console.log(req.body);
res.end();
//then respond by running function AddFlashCard(event)
})
HTML FORM CODE:
<form id="form-container" method="post">
<div class="justify-container">
<div class="formItem" id="box1">
<label for="card-title-input" class="label" id="card-title-label">Card Title:</label>
<input type="text" name="title" id="card-title-input">
</div>
<div class="formItem" id="box2">
<label for="card-front-input" class="label">Card Front:</label>
<textarea name="front" id="card-front-input" cols="30" rows="5" maxlength="160"></textarea>
</div>
<div class="formItem" id="box3">
<label for="card-back-input" class="label">Card Back:</label>
<textarea name="back" id="card-back-input" cols="30" rows="5" maxlength="160"></textarea>
</div>
<div class="formItem" id="box4">
<button type="submit" id="submit">Add Card</button>
</div>
</div>
</form>
After clicking my submit button, page goes blank, and node server outputs as an example,
[Object: null prototype] {
title: 'Title',
front: 'Front',
back: 'Back'
}
This is just the first step of it and not supposed to be fully functional given this code ofcourse, I would just like to start with getting this example data sent with from the form to the server and the page not going blank and functioning otherwise normally.
remove body-parser use only express.json()
I want to add an input box (a placeholder) where the user could paste a screenshot into. img is not going to do it as it requires the screenshot to be saved into an image file, then the scr be directed to it. Too cumbersome. I want a simple copy (or print screen) and paste to do it.
I modified the code from the following discussion:
HTML Paste Clipboard Image to File Input,
but it does not work.
<form id="new_document_attachment" method="post">
<div class="actions"><input type="submit" name="commit" value="Submit" /></div>
<img src="" alt="Screen Shot" id="image_attachment_doc">
</form>
<script>
const form = document.getElementById("new_document_attachment");
const imageInput = document.getElementById("image_attachment_doc");
imageInput.addEventListener('change', () => {
form.submit();
});
window.addEventListener('paste', e => {
imageInput.src = e.clipboardData.files;});
</script>
You need to convert the image data in the File object into a Data URL.
Thanks to Loading an image to a <img> from <input file>
Your example is also a bit limited in that although the image would show up, the page would reload almost immediately.
In the example below the form is not submitted.
const log = document.getElementById("log");
window.addEventListener('paste', e => {
var files = e.clipboardData.files;
//Put the file into an input so it will be included with the form submit
document.getElementById("files").files = files;
//This won't work because the src holds a string
//and the file object becomes serialized into "[object%20File]"
//This can be seen in the console
document.getElementById("img").src = files[0];
//Show image by loading it as an DataURL
var fr = new FileReader();
fr.onload = function() {
document.getElementById("img").src = fr.result;
}
fr.readAsDataURL(files[0]);
});
<form id="form" method="post">
<img id="img" alt="Screen Shot">
<input type="file" name="files" id="files" />
<input type="submit" />
</form>
<p>Press Ctrl+V to paste an image into this window</p>
I'm using Node.js on Google cloud with Firebase Realtime Database.
I can write and read data from server.js to the actual Firebase real-time database.
const express = require ('express');
const path = require('path');
var firebase = require("firebase-admin");
var serviceAccount = require("./srverKey.json");//path to key file
//Instantiate express
const app = express();
//Set URL routes
app.use('/static', express.static('public'))
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, '/index.html'));
})
//Instantiate firebase Admin
firebase.initializeApp({
credential: firebase.credential.cert(serviceAccount),
databaseURL: "https://something.firebaseio.com"
});
// Get a database reference to our posts
var db = firebase.database();
//create a sample message
var message = {text: 'hello', timestamp: new Date().toString()};
var ref = firebase.database().ref().child('node-client');
var logsRef = ref.child('logs');
var messagesRef = ref.child('messages');
//below .push creates a new record with a new key
var messageRef = messagesRef.push(message);
logsRef.child(messageRef.key).set(message);
logsRef.orderByKey().limitToLast(1).on('child_added', function(snap){
console.log('added', snap.val());
});
logsRef.on('child_removed', function(snap) {
console.log('removed', snap.val());
});
ref.child('logs').on('child_changed', function(snap) {
console.log('changed', snap.val());
});
ref.child('logs').on('value', function(snap) {
console.log('value', snap.val());
});
<form>
<label for="userId">User ID</label><br>
<input type="text" name="userId" id="userId"><br>
<label for="firstName">First Name</label><br>
<input type="text" name="firstName" id="firstName"><br>
<label for="lastName">Last Name</label><br>
<input type="text" name="lastName" id="lastName"><br>
<label for="age">Age</label><br>
<input type="number" name="age" id="age"><br>
<button id="addBtn" class="btn waves-effect waves-light">Add</button>
<button id="updateBtn" class="btn waves-effect waves-light">Update</button>
<button id="removeBtn" class="btn waves-effect red darken-1">Remove</button>
</form>
However I can't figure out how the hell people pass values from index.html to server.js in order to store them in firebase.
When you connect from a privileged environment (google cloud) you use different code to connect than when from your own server therefore the examples under:
https://firebase.google.com/docs/samples/
are useless to me. They connect from public HTML javascript to the database where as in a 'privileged environment' you connect from the server-side script.
how do you read the from data from server.js?
How do you call a function to read the form from the html?
In say PHP you would post the form to a link.
What I'm looking for here is middleware called 'body parser'
npm install body-parser
I am having the same issue; however, I think your comment and answer get it correct: you have to have a POST method on form submit, and this route and method can be accommodated by Express in server.js. You can then pass this data to Google Cloud.
EDIT: Edited it using Mikhail's suggestion. Got closer to the solution
Hi I am trying to upload a JSON file using nodejs but for some reason it says my file is undefined. A file appears in my Public folder that contains the contents of the uploaded file however. I was wondering if someone would be able to help me out. Thanks
Here is the HTML
<form method="post" enctype="multipart/form-data" action="/file-upload">
<input type="file" name="theFile" >
<input type="submit" class = "submit">
</form>
EDIT: Here is the server.js
app.post('/testtwilio',upload.single('theFile'),function(req, res, next) {
console.log('FIRST TEST: ' + req.file);
});
Here is the JSON file
[{"name":"FIRST LAST","date":"12/22/2016","number":"7523924324"}]
Here is what is being logged
FIRST TEST: [object Object]
Change your JSON.stringify(req.files) to JSON.stringify(req.file)
Full code
HTML
<form id = "uploadForm" enctype = "multipart/form-data" action = "/api/file" method = "post">
<input type="file" name="userFile" />
<input type="submit" value="Upload File" name="submit">
</form>
JS
var express = require('express')
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
var app = express()
app.get('/',function(req,res){
res.sendFile(__dirname + "/index.html");
});
app.post('/api/file', upload.single('userFile'), function (req, res, next) {
console.log(JSON.stringify(req.file))
})
app.listen(3000,function(){
console.log("Working on port 3000");
});
Note:
File name which you use in multer.single() method should match name in input <input type="file" name="userFile" />
If you use the .single(...) method the file will be in req.file.
I'm working on a project that I need from login, to compare the information at the form with the database. And later, after doing the validation, I need to load the information of a login in another page (I have no idea how).
(I tried to find some tutorials, but all of them use Express, that I'm not allowed to)
Now my code:
HTML (I think this part is OK, cause I could save the information in $scope.u)
<form ng-controller = "login" ng-submit="submit(user)">
<label>Login:</label>
<input type="text" ng-model="user.login" required>
<label>Senha:</label>
<input type="password" ng-model="user.pwd" required>
<label><input type="checkbox"> Lembre-me</label>
<button type="submit" class="btn btn-default">Login</button>
<p>{{user.login}}</p>
<p>{{user.pwd}}</p>
<p>LOGIN:{{user.login}}</p>
<p>SENHA:{{user.pwd}}</p>
</form>
Angular (I'm not sure if I understood the idea of $http.post, so I don't know if I can send the info of $scope.u to Nodejs)
app.controller('login',function($scope,$http){
$scope.u = {};
$scope.submit = function(user) {
$scope.u = angular.copy(user);
console.log($scope.u);
};
$http.post('/servico/login', $scope.u).success(function(data, status) {
console.log('Data posted successfully');
});
});
Node (If I could use the information of $scope.u, my problem would be finished there, but I don't know how I can load the information in another page)
The button Login should compare the values from the form and them, maybe, use to send to the other page.
function login(request,response){
var queryString = 'SELECT uLogin,uSenha FROM usuarios';
connection.query(queryString,function(err,rows){
});
}
I hope I've been clear with my doubt.
Thanks for your help.