0

Hi i am trying file uploading(image) in node.js with express.This is far i have done.

my app.js

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);
});

my html file:

<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" />
        <div id="fileName"></div>
        <div id="fileSize"></div>
        <div id="fileType"></div>
        <div id="progress"></div>
<img src="images/ajax-loader.gif" id="loading-img" style="display:none;" alt="Please Wait"/>
</form>

I am now able upload file.But i want to do this with ajax without reloading page.Please help to give information to do this.Any help would be appreciated.

Coder
  • 23
  • 1
  • 9
  • What browsers do you need to support? – Explosion Pills Jun 01 '14 at 14:07
  • Mostly all i know about IE – Coder Jun 01 '14 at 14:26
  • @user3689905 The limitation will be with `type="file"`. Ajax itself didn't support transporting files until [XMLHttpRequest Level 2](http://www.w3.org/TR/XMLHttpRequest2/), and only [IE10 and later supports that](http://caniuse.com/#feat=xhr2). For a "how to," see [MDN's Using FormData Objects](https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects). – Jonathan Lonowski Jun 01 '14 at 15:54

0 Answers0