0

我正在尝试使用filefieldExtJS 上传图像文件并将其作为form服务器端(“Express”)提交。我在下面粘贴了我的代码:

我尝试为 req.body 引用 API,req.body总是undefined. 请让我知道我在哪里做错了。 外部 JS 代码

 {
    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;
                    }
                }
            }
    }]
}

快递代码: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;

注:Express 版本:“express”:“~4.13.1”

Express 4x API

4

1 回答 1

0

我不确定这是最好的方法,但以下步骤有效!

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

粘贴以下内容

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

保存包文件

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

保存文件 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

浏览http://localhost:8097/

于 2015-08-17T07:55:33.193 回答