Upload Files using Express + Connect (Node) - node.js

I'm trying to upload files via a web site. As I'm new in web programming, I didn't found a full example in web that solves all my doubts.
My scenario is:
Nodejs (v.0.10.25) + Express (4.9.0)
Trying to use Connect (3.0).
I created my app using the Express command. So the app.js was created default. I figured out that Express doesn't have multipart by default. And I should install a middleware to use it.
I'm trying to install Connect. The question is: How do I configure it? Must I have to replace the Express server for Connect server or it can exist together ?
Some one can explain how does it works ? Or show an example ?
Thanks too much!

via http://howtonode.org/really-simple-file-uploads
<!-- client html -->
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file_upload">
</form>
// node.js server
var fs = require('fs'),
http = require('http');
app = (require('express'))();
app.post('upload', function(req, res){
fs.readFile(req.files.file_upload.path, function (err, data) {
var newPath = __dirname + "/uploads/uploadedFileName";
fs.writeFile(newPath, data, function (err) {
res.redirect("back");
});
});
});

Related

Node.js application to accept JSON from user, manipulate and save to MSSQL

I'm stuck. I thought my goal was going to be straight forward but I appear to be missing some key piece.
I'm trying to build a website that can accept a JSON file from an end user. Once the file has been provided I want to combine that data with data from a web-resource and then take the resulting flattened JSON and write it to a database table.
The first prototype of the project was built in a single HTML page with some JavaScript and I succeeded in getting the output the way I wanted it to look.
Then I tried to convert it to a node.js server so I could use an API to write the resulting JSON to the SQL server.
While the problem with which I am asking for help does not involve those steps I just wanted to share that there are some complexities of async that are possibly muddying things.
I've tried creating an HTML page that accepts a file and using express tried to capture that file, but I can't seem to figure out the right combination of middleware and other code to get the JSON file loaded into an object so I can feed it to my existing function to manipulate it and then subsequently feed it to a function to write it to SQL using a stored procedure.
So here's what I've got for my index.js
const express = require("express");
const app = express();
const fileUpload = require('express-fileupload');
const bodyParser = require("body-parser");
const path = require("path");
app.use(express.urlencoded({
extended: false
}));
app.use(express.json());
app.use(fileUpload());
app.post('/upload', function(req, res) {
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send('No files were uploaded.');
}
let jsonFile = req.body.sampleFile;
console.log(jsonFile);
let parsed = JSON.parse(jsonFile);
console.log
res.send("blank page");
});
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/minimalIndex.html'));
});
const webserver = app.listen(5000, function() {
console.log('Express web server is running..');
});
and the HTML that it uses is this
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Static Index.html</title>
</head>
<body>
<form ref='uploadForm' id='uploadForm' action='/upload' method='post' encType="multipart/form-data">
<input type="file" name="sampleFile" />
<input type='submit' value='Upload!' />
</form>
</body>
</html>
The console.log shows undefined.
The JSON Parse fails because of an invalid JSON string.
I've succeeded at saving the file locally but that seems unnecessary.
Can someone please tell me what it is I am missing?
Everything is correct apart from the way you are trying to fetch the files. You are trying it from body while it should be from files. Something like this
let jsonFile = req.files.sampleFile;
let parsed = JSON.parse(jsonFile.data.toString("utf-8"));
Hope it helps

Cannot POST /addfriend error using Express

I am trying to create a simple form handler using express. Here is a similar question but I can't related it with my problem. I have written all of my file Here anyone can check it by using all of my file. For better understanding I copy my code here:
app.js code:
const express = require('express');
const app = express();
//routes
app.get('/',function(req,res){
res.send('This is root dir');
});
app.get('/friends',function(req,res){
var friends=['sakib','emon','rayhan'];
res.render('friends.ejs',{friends:friends});
});
app.get('/addfriend',function(req,res){
res.send('ADD friend page launch!!!!!');
});
app.listen(3000,function(){
console.log("server has started on port 3000!!!");
});
ejs(friends.ejs) code:
<h1>Here is list of your Friend:</h1>
<%friends.forEach(function(friend){%>
<li><%=friend%></li>
<%});%>
<form action="/addfriend" method="POST">
<input type="text" name="friend" placeholder="name">
<button>
Submit
</button>
</form>
When I type any name in the input box and clicked Submit it didn't post to /addfriend. I didn't understand where is my problem. Please goto input box(link) after started the server.
For better understand what's my actual problem is then please use goorm IDE(shared file) where I uploaded everything.
You are using get request instead of post for addfriend.
app.post('/addfriend',function(req,res){
console.log("I'm called wohoo!");
res.send('ADD friend page launch!!!!!');
});

Formidable upload file don't trigger

Development and test environment:
Windows 8 64bit
node version installed 0.10.5
npm version 1.2.18
express framework
formidable module used for file uploading
Firefox and Internet Explorer browsers
HTML code:
<form id="caricaMasterImg" method="post" enctype="multipart/form-data" action="/image/upload">
<input type="file" id="masterImg" name="masterImg" value="Sfoglia" accept="image/*"/>
<input type="submit" value="carica" id="submitLoadImg" />
</form>
app.js code:
var image = require('./route/image');
app.post('/image/upload', image.upload);
routes/image.js code:
exports.upload = function(req, res){
var form = new formidable.IncomingForm();
form.uploadDir = path.join(__dirname, 'tmp');
console.log('Upload directory is: '+form.uploadDir);
fs.exists(form.uploadDir, function (exists) {
console.log('is an existing directory? '+exists);
});
form.parse(req, function(err, fields, files) {
console.log(fields);
console.log(files);
});
};
The issue:
When submit button is clicked I expect to see the file logged with console.log(files) instruction. Log writes:
Upload directory is: C:\Liber-I\app\FileSystemManager\routes\tmp
is an existing directory? true
No more log is written on application console for several minutes.
I test the case of no-file submission and it seems it is acting the same! It is a too weired behaviour to be a nodejs problem, where am I doing wrong?
I think I did nothing wrong. Truth is I am not able to fix this problem, so I decided for a good work around. I choose to use connect-multiparty for file uploading and it is working just great.

How can I get the "name" attribute in node.js

<input type='file' name='upload1'/>
When this form is submitted,how can I get the "name" attribute (upload1) on node.js.
I use restify,and upload image.
The right way in node.js is would be to use a web app framework like express. It gives you more options as well as flexibility. In express you can do :
var express = require('express'); //Initialize express
var app = express();
app.listen(3000);
app.use(express.bodyParser()); //to parse the forms
app.post('/pagesubmit', function(request, response){ //to handle POST to the page
console.log(request.body.username); //tp access input text 'username'
console.log(request.files.name); //to access input file 'name'
});
Just use node-formidable for file uploads.

Node.js - socket.io web app

I've created a basic node.js server program and used socket.io to pass some field data from a client (see below). Pretty chuffed as I'm new to this business. I liked this node-express-socket.io approach as its all Javascript and is apparently usable by most browsers (incl' mobile). The problem is I've kind of fumbled my way through and do not not fully understand what I have created! Two questions...
1) Do I need to use the "//ajax.googleapis.com...jquery..."? This is annoying as the browser will need to have an internet connection to work. Is there another way to access the html doc elements without needing an internet connection?
2) What does the "app.use(express.static...." line do? The "app.get..." function seems to require this to work.
If there are any other general comments about my code please let me have it!
Cheers,
Kirbs
Client side code:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect(document.location.protocol+'//'+document.location.host);
function clicked(){
$(function(){
var makeInput=$('.app').find('#make').val();
var modelInput=$('.app').find('#model').val();
socket.emit('make', makeInput);
socket.emit('model', modelInput);
});
};
</script>
Server side code:
var express = require('express');
var http = require('http');
var socketio = require('socket.io');
var app = express();
var server = http.createServer(app);
var io = socketio.listen(server);
app.use(express.static(__dirname));
app.get('/', function (req, res) {
res.render(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.on('make', function (make) {
socket.on('model',function (model){
console.log('recieved message:', make+','+model);
});
});
});
server.listen(8000);
1) As you have setup a static web server (see answer 2), you could simply download the jquery source and serve the .js file from there.
2) "app.use(express.static...." configure a static webserver and setting up the http root directory to the directory that your node.js script lives, as indicated by the __dirname variable. For more detail, see app.use API reference.
As result, I would recommend you change you app.use to:
app.use(express.static(__dirname + '/public'));
and place all your static files, including your jquery file(s), under a public subdirectory.
Also, your server side code has a dependency on sequence of make and model which should be changed. For example, if you switch the emit order to model then make, you should see that your server's console.log will be picking up the make from the previous call.
Instead, try something like:
// On server:
socket.on('info', function (info) {
console.log('recieved message:', info.make+','+info.model);
});
// On client:
socket.emit('info', { make: makeInput, model: modelInput })
1) You can serve the jQuery library also from your server if you like that better. You should put it in the public/vendor or public/js folder in your project.
2) This is a middleware call from Express framework, which uses in turn the Connect middleware stack. Read up on this here.

Resources