Multer一直给我不明确的

时间:2016-03-24 09:48:09

标签: node.js multer

我希望使用Multer将图像文件上传到我的节点服务器上。代码很简单,我从Multer的文档中复制了它。我花了一整天的时间来解决这个问题,它总是回过头来给我一个未定义的使用ajax来发送图像。

使用表单进行工作multer - req.file always undefined

但是,我很想知道是否有人成功使用ajax方式发送文件。

HTML

<input type="file" id="avatar" name="avatar"/>

当用户点击按钮并选择文件时,我只显示文件信息,并使用ajax将数据发送到我的节点路由器 http://localhost:8882/profile

JS

<script>
//files structure contains data about each file you load in
   document.getElementById('avatar').addEventListener('change', function() {

    var file = this.files[0];
    console.dir(this.files[0]);

    postItem(this.files[0]);

}, false);


function postItem(imageObj) {
  console.log("postItem <----");
    $.ajax({
        type: "POST",
        url: "http://localhost:8882/profile",
        contentType:false,
        cache: false,
        processData: false,
        data:  imageObj,
        success: function(data) {
            //show content
            alert('Success!');
        },
        error: function(jqXHR, textStatus, err) {
            //show error message
            alert('text status ' + textStatus + ', err: '+err);
        }

    }); //ajax
}//postItem()

</script>

在Node端,代码直接来自multer的文档: https://www.npmjs.com/package/multer

我一直在为req.file定义未定义。

节点

var express     = require('express');
var app         = express();
var bodyParser  = require('body-parser');
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })

app.post('/profile', upload.single('avatar'), function (req, res, next) {
    console.log("------ /profile --------");

    if(req) {
        console.dir(req.file);
    }

    console.log("------------------------");
    res.send({"message":"ok"});
});

app.listen(8882);
console.log("index.js - listening on port " + 8882);
exports.app = app;

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:3)

您可以使用FormData通过ajax提交整个表单以及图片。

脚本它使用 jQuery

$(function(){
   $('form').submit(function(e){

      //formData sets: multipart/form-data
      var formData = new FormData($(this)[0]);
      $.ajax({
          type:'POST',
          url:'http://localhost:3000/uploads',
          data : formData,                  
          contentType: false,
          processData: false
      }).done(function(data){
          //print response on success
          console.log(data);

      }).fail(function(data) {
            console.log('Error');
        });
      e.preventDefault(); 
    });
})();   

HTML表单示例代码:

<form>            
    <label for="userName">Name</label>
    <input type="text" name="userName"/>
    <br>
    <label for="phoneNumber">PhoneNumber</label>
    <input type="text" name="phoneNumber"/>
    <br>
    <label for="file">UploadFile</label>
    <input type="file" name="avatar"/>
    <input type="submit"/>
</form>

Node.Js 示例代码,您可以设置文件名以便于访问:

//file upload module
const storage = multer.diskStorage({
    destination :function(req,file,cb){
        cb(null,'./uploads');
    },
    filename : function(req,file,cb){
        cb(null,req.file.originalname+'.jpg');
    } 
});

var upload = multer({storage:storage}).single('avatar');

app.post('/uploads',upload,(req,res)=>{

    res.json({
     "fileName":req.file.originalname,
     "userName":req.body.userName,
     "phoneNumer":req.body.phoneNumber     
    });
});

答案 1 :(得分:2)

您的node.js代码正在提供undefined,因为file对象req对象附加'multipart/format-data',这没有任何问题。 multer中间件仅解析file,如果数据是任何其他格式,则multer在不添加'multipart/format-data'对象的情况下传递请求,因此req.file未定义。因此,要使代码正常工作,您需要在SELECT SUM(CASE WHEN TO_CHAR (start_date, 'FMDay') = 'Sunday' THEN ROUND ( (completion_date - start_date) * 24, 1) END) AS "Sunday", SUM(CASE WHEN TO_CHAR (start_date, 'FMDay') = 'Monday' THEN ROUND ( (completion_date - start_date) * 24, 1) END) AS "Monday", SUM(CASE WHEN TO_CHAR (start_date, 'FMDay') = 'Tuesday' THEN ROUND ( (completion_date - start_date) * 24, 1) END) AS "Tuesday", SUM(CASE WHEN TO_CHAR (start_date, 'FMDay') = 'Wednesday' THEN ROUND ( (completion_date - start_date) * 24, 1) END) AS "Wednesday", SUM(CASE WHEN TO_CHAR (start_date, 'FMDay') = 'Thursday' THEN ROUND ( (completion_date - start_date) * 24, 1) END) AS "Thursday", SUM(CASE WHEN TO_CHAR (start_date, 'FMDay') = 'Friday' THEN ROUND ( (completion_date - start_date) * 24, 1) END) AS "Friday", SUM(CASE WHEN TO_CHAR (start_date, 'FMDay') = 'Saturday' THEN ROUND ( (completion_date - start_date) * 24, 1) END) AS "Saturday" FROM emp_dates; Sunday Monday Tuesday Wednesday Thursday Friday Saturday ---------- ---------- ---------- ---------- ---------- ---------- ---------- 3.1 4.9 中发送文件。此链接有助于发送正确的ajax请求Sending multipart/formdata with jQuery.ajax

希望它有所帮助:)