Hello friends,
I am newbie to Node.js.When i tried to make a simple image uploading script. I find more difficulty to find exact resources or good tutorials because most of them are depreciated. Finally after a full day research,I somewhat made my file uploading script.I found that if i share somewhere on the internet,It will be useful for others.So started this blog. Going to share my experience with node in this blog.
Now the script as follows.
This is my html file
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>File Upload showing Upload Progress</title>
<style>
* {
font-family: Verdana;
font-size: 12px;
}
</style>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data" id="uploadForm">
<input name="ImageFile" id="imageInput" type="file" />
<input type="submit" id="submit-btn" value="Upload" />
</form>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.min.js'></script>
</body>
</html>
and my app.js (you can name it as you want like server.js or anything you want)
var express = require('express'); //Express Web Server
var bodyParser = require('body-parser'); //connects bodyParsing middleware
var formidable = require('formidable');
var path = require('path'); //used for file path
var fs =require('fs-extra'); //File System-needed for renaming file etc
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
/* ==========================================================
bodyParser() required to allow Express to see the uploaded files
============================================================ */
app.use(bodyParser({defer: true}));
app.route('/').get(function(req,res)
{
console.log("Server started!");
res.render('index.html');
res.end('done');
});
app.post('/upload', function(req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
var targetPath= '/upload/' + files.ImageFile.name;
fs.move(files.ImageFile.path, __dirname + '/upload/' + files.ImageFile.name, function(err) {
if (err) return console.log(err);
console.log('Moved successfully');
});
res.send('File Uploaded to ' + targetPath + ' - ' + files.ImageFile.size + ' bytes');
});
});
var server = app.listen(3030, function() {
console.log('Listening on port %d', server.address().port);
});
To get this work successfully.Create a upload folder in your project.This script simply allows you to make file uploaded from form to server.As my next step, I am trying to do with this ajax and some more form validation.Hope soon will hit with that.
If you have any question,feel free to ask me.If i able to answer, i will surely help you guys.If you found this helpful share it with your friends and subscribe.