使用multiparty未定义文件

时间:2016-02-22 20:11:18

标签: javascript node.js express

我想使用node.js上传img,我使用express和multiparty,我的代码看起来像

HTML

<!DOCTYPE html>
<html>
<body>

<form  method="post" action="/img">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>

JS

  var express  = require("express");
var app=express();
var http=require("http").Server(app);


app.get("/",function(req,res){
    res.end("hello")
});

app.get("/upload",function(req,res){
    res.sendFile(__dirname + "/form.html")
})
app.post("/img",function(req,res){
    var multiparty = require("multiparty");
    var form = new multiparty.Form();

    form.parse(req,function(err,fields,files){
        var img = files.images[0];
        console.log(img)
    })


})
http.listen(3000,function(){
    console.log("listening on 3000")
})

当我上传某些内容时,会抛出错误

  

无法读取未定义的属性图像

作为后端的新手我不知道为什么会发生这种情况,目录img存在于html和js所在的文件夹中。

2 个答案:

答案 0 :(得分:0)

将enctype添加到表单:

<form  method="post" action="/img" enctype="multipart/form-data">

PS:对于上传图片,建议您使用formidable,有些像this

答案 1 :(得分:0)

您可以使用multer上传文件,请参阅下面的代码,前端:

<html>
<head>
<title>FileUpload</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<form id       =  "uploadForm"
     enctype   =  "multipart/form-data"
     action    =  "http://localhost:3000/api/photo"
     method    =  "post"
>
<input type="file" name="userPhoto" multiple />
<input type="submit" value="Upload Image" name="submit" id="btnUpload">
<span id="spnStatus" />
</form>

<script>
        $(document).ready(function(){
            $('#btnUpload').click(function(){
                $('#spnStatus').empty().text("File is Uploading");
                $(this).ajaxSubmit({
                 error : function(xhr){
                    status('Error : '+xhr.status);
                    }

                 success : function(response){
                    $('#spnStatus').empty().text(xhr);
                    }
                });
            });

        });
    </script>
</body>
</html>

NodeJS:

var express =   require("express");
var multer  =   require("multer");
var bodyParser =    require("body-parser");
var app =   express();
app.use(bodyParser.json());

 var storage =   multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './uploads');
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + '-' + Date.now());
  }
});
var upload = multer({ storage : storage }).array('userPhoto',1);

app.get('/',function(req,res){
      res.sendFile(__dirname + "/fileUpload.html");
});

app.post('/api/photo',function(req,res){

          upload(req,res,function(err) {
            if(err) {
                return res.end("Error uploading file.");
            }
            res.end("File is uploaded");
         });
});

app.listen(3000,function(){
    console.log("Working on port 3000");
});

如果需要,您可以同时上传多个文件,例如将userPhoto增加到5 var upload = multer({ storage : storage }).array('userPhoto',5);