2016-11-08 131 views
1

我在尝试使用Node.js服务器上传文件的API。我得到undefined的回应。用HTML上传文件到Node.js

我下面这个教程https://www.youtube.com/watch?v=UtfZ-5WKpro

的Node.js:

var express = require('express'); 

var app = express(); 
var bodyParser = require('body-parser'); 

app.use(bodyParser.json()); 

app.post("*", function(req, res) { 
    res.end(JSON.stringify(req.files) + "\n"); 
}); 

console.log("Server at 8080"); 
app.listen(8080); 

HTML

<html> 
    <head> 
    <form method="post" 
      enctype="multipart/form-data" 
      action="http://localhost:8080"> 
     <input type="file" name="myimage" /> 
     <input type="submit" name="submit" value="submit"/> 
    </form> 
    </head> 
</html> 

点击提交我undefined响应后。

回答

5
bodyParser.json() 

...所以你已经设置了一个解析器JSON格式的请求

enctype="multipart/form-data" 

...但你是不是做一个JSON格式的请求。

the documentation for body-parser

这不处理多机构,由于其复杂的,通常大的性质。对于多部分机构,您可能对以下模块感兴趣:

...其后是建议列表。

选择一个可处理多部分请求并使用该模块的模块,而不是您当前的选择。

1

我建议您使用this module来处理Node/Express中的文件上载。

var fileupload = require('fileupload').createFileUpload('/uploadDir').middleware; 

app.post('/upload', fileupload, function(req, res) { 
    // files are now in the req.body object along with other form fields 
    // files also get moved to the uploadDir specified 
}); 

另一种方式来上传文件可以使用这样的事情

玉模板

form.data(action='/user/register', method='post', class="long-fields", enctype='multipart/form-data') 
    input(type="text" name="name") 
    input(name='fileLogo', type='file') 
    input(type="submit" value="Register") 

控制器

formidable = require('formidable'); //file upload handling via form 
uuid = require('node-uuid'); //Unique ID 
path = require('path'); //Path compiler 
fs = require('fs'); //FileSystem 

var form = new formidable.IncomingForm(); 
form.keepExtensions = false; 
form.maxFieldsSize = 2 * 1024 * 1024; //2mb 

form.parse(req, function(err, fields, files) { 

    console.log(fields); 
    console.log(files); 

    fs.readFile(files.fileLogo.path, function (err, data) { 
    var pathNew = __dirname + '/../../uploads/' + uuid.v1() + path.extname(files.fileLogo.name); 

    fs.writeFile(pathNew, data, function (err) { 
     console.log('uploaded', pathNew); 
    }); 
    }); 

    res.send(jade.renderFile(settings.pathLess + prefix + '/register.jade', { 
    req: req 
    })); 

});