坚持试图超越这个。应该是微不足道的,但我显然做了一些愚蠢的事情。目标是在Express中上传文件。简而言之,文件在路由处理程序中以未定义的形式返回:
//modules ==========================================
// ExpressJS 4.0 used for the middleware and web framework
var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var flash = require('connect-flash');
var jsxml = require("node-jsxml");
var XMLWriter = require('xml-writer');
var request = require("request");
var fs = require('fs');
var app = express();
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
// Did I screw this up??!
app.use(bodyParser({keepExtensions:true,uploadDir: __dirname + '/public/uploads'}));
app.engine('html', require('ejs').renderFile);
app.use(cookieParser('Ronaldinho'));
app.use(session());
app.use(flash());
我的文件系统:
这是提交文件的表单(通过名为DropZone的插件):
<div id="dropzone">
<form action="/uploads" name="upload" class="dropzone" id="demo-upload" enctype="multipart/form-data" method="post">
<input type="file" name="theFile" />
</form>
</div>
和路线的处理程序:
app.post('/uploads', function (request, response) {
console.log('arrived');
console.log('1st TEST: ' + (request.files));
console.log('2nd TEST: ' + request.files.theFile.name);
fs.readFile(request.files.theFile.path, function (err, data) {
var newPath = "/home/path/to/your/directory/"+request.files.theFile.name;
console.log (newPath);
fs.writeFile(newPath, data, function (err) {
res.send("hi");
});
});
});
每次上传文件时都会点击上面的函数,但是发现request.files是未定义的。这是控制台上的结果(我使用Brackets - 对我来说很有趣,我从来没有看到第二次测试到达控制台窗口......):
我搞砸了什么想法?