Arnold
Arnold

Reputation: 210

how to upload mulitiple file with expressjs?

this is my html

<form action="/keys/upload" method="post" enctype="multipart/form-data">
<ul>
        <li><label>文件</label><input type="file" name="keys" multiple></li>
        <li><input type="submit" value="submit"></li>
</ul>
</form>

this is my handle function

app.post('/keys/upload',keysRoutes.addKeys);

var addKeys=function(req,res){
    var temppaths=req.files.keys[0].path;
    console.log(temppaths);
    res.end(JSON.stringify(temppaths));
};

here if i upload more than one file,then req.files.keys[0].path works fine,but when i only upload one file,it goes wrong,i have to replace it as req.files.keys.path. i don,t know how many files will be upload,so what should i do?

sometimes req.files.keys is array,sometimes req.files.keys is object.

Upvotes: 0

Views: 113

Answers (2)

Arnold
Arnold

Reputation: 210

I find a method,I think I can use

var paths=[].concat(paths);

then paths will always be an array

Upvotes: 0

robertklep
robertklep

Reputation: 203304

Seems to me that you should check if it's an array or an object; when it's not an array, wrap it into one:

var paths = req.files.keys || [];

if (! (paths instanceof Array) ) {
  paths = [ paths ];
}

Upvotes: 1

Related Questions