0

I am trying to use filefield of ExtJS to upload an image file and submit it as a form to server side ("Express"). I have pasted my code below:

I tried referring API for req.body but req.body is always undefined. Please let me know where I am doing wrong. Ext JS Code

 {
    xtype: 'form',
    name:'imageForm',
    items:[{
            xtype:'textfield',
            name:'name',
            value:'Krisna'
        },{
            xtype: 'filefield',
            hidden: false,
            buttonOnly:true,
            buttonText:'Change Photo',
            name: 'imageUrl',
            //bind: '{currentContact.imageUrl}',
            listeners:{
                change:function(fielField, value){
                    var filePath = value;
                    fileNameIndex = filePath.lastIndexOf("\\");
                    fileName = filePath.substring(fileNameIndex + 1);
                    fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
                    var form = this.up('form').getForm(); // working
                    if(fileExt === 'jpeg' || fileExt === 'jpg' || fileExt === 'gif' || fileExt === 'png'){
                        if (form.isValid()) {
                            form.headers = {
                                'Content-Type' : 'application/json;charset=utf-8',
                                "Accept" : "application/json;charset=utf-8"
                            };
                            form.submit({
                                url : 'http://localhost:3000/changePhoto',
                                waitMsg : 'Uploading your Photo...',
                                success : function (fp, o) {
                                    Ext.Msg.alert('Success', 'Your Photo has been uploaded.');
                                    //Write code here to set the server side image url so that that image gets displayed , but not as fakepath.
                                },
                                failure : function (fp, o) {
                                    Ext.Msg.alert('Failed', 'Your Photo failed to uploaded.');
                                }
                            });
                        }
                    }
                    else if(value){
                        //showOKInfoMsg(SWP_Msg.SWP_CompressFileFrmtMsg);
                        Ext.Msg.alert('Warning', 'Please select Image file only');
                        this.reset();
                        return true;
                    }
                }
            }
    }]
}

Express code: index.js:

var express = require('express');
var router = express.Router();

var bodyParser = require('body-parser');
router.use(bodyParser.json()); // for parsing application/json
router.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

//var multer  = require('multer');    // tried using multer, but I think this is only for file upload not form submit
//var temp = multer();          

//router.use(bodyParser());
//router.use(multer()); // If I try adding multer at this line it is throwing error 

router.post('/changePhoto',  function (req, res) {
  console.log(req.body);  // Outputting {} i.e., empty object

  var userName = req.body.name; // coming undefined as req.body is undefined
  res.json(req.body); // sending back {}
});

module.exports = router;

Note: Version of Express: "express": "~4.13.1"

Express 4x API

vajrakumar
  • 758
  • 2
  • 7
  • 21
  • The best way is to use multer. You can submit other form components and file separately. –  Aug 12 '15 at 09:53
  • When I tried Uncommenting lines : var multer = require('multer'); router.use(multer()); following error it is throwing, "throw new TypeError('Router.use() requires middleware functions'); ^ TypeError: Router.use() requires middleware functions. " I have already installed multer – vajrakumar Aug 12 '15 at 10:03

1 Answers1

0

I am not sure this is the best way of doing it, But following steps works!

mkdir fileuploaderwebapp && cd fileuploaderwebapp && vi package.json

paste the following

{
  "name": "uploader",
  "version": "0.0.1",
  "dependencies": {
    "express": "~4.10.2",
    "multer": "~0.1.6"
  }
}

Save the package file

npm install

vi uploader.js

/*Define dependencies.*/

var express=require("express");
var multer  = require('multer');
var app=express();
var done=false;

/*Configure the multer.*/

app.use(multer({ dest: './uploads/',
 rename: function (fieldname, filename) {
    return filename+Date.now();
  },
onFileUploadStart: function (file) {
  console.log(file.originalname + ' is starting ...')
},
onFileUploadComplete: function (file) {
  console.log(file.fieldname + ' uploaded to  ' + file.path)
  done=true;
}
}));

/*Handling routes.*/

app.get('/',function(req,res){
      res.sendfile("uploadmain.html");
});

app.post('/api/fileuploader',function(req,res){
  if(done==true){
    console.log(req.files);
    res.end("File uploaded.");
  }
});

/*Run the server.*/
app.listen(8097,function(){
    console.log("Working on port 8097");
});

Save the file uploader.js

vi uploadmain.html

<form id        =  "multipartform"
     enctype   =  "multipart/form-data"
     action    =  "/api/fileuploader"
     method    =  "post"
>
<input type="file" name="filecomp" />
<input type="submit" value="Upload" name="submit">
</form>

node uploader.js

Browse http://localhost:8097/

rbyndoor
  • 699
  • 4
  • 14