这是 HTML 代码:
File Uploading FormSelect a file to upload:
enctype = "multipart/form-data">
这是 NodeJs 代码:-
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/tmp/'})).single('file'));//I have added this, this is also a mistake by them (tutorialpoint.com)
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.post('/file_upload', function (req, res) {
console.log(req.files.file.name);
console.log(req.files.file.path);
console.log(req.files.file.type);
var file = __dirname + "/" + req.files.file.name;
fs.readFile( req.files.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if( err ){
console.log( err );
}else{
response = {
message:'File uploaded successfully',
filename:req.files.file.name
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
})
var server = app.listen(8050, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
这是我的日志:-
Example app listening at http://localhost:8050
TypeError: Cannot read property 'file' of undefined
at C:\Users\devuser\Desktop\nodejsPrograms\filenew\server.js:17:25
at Layer.handle [as handle_request] (C:\Users\devuser\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\devuser\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch (C:\Users\devuser\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\devuser\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\devuser\node_modules\express\lib\router\index.js:277:22
at Function.process_params (C:\Users\devuser\node_modules\express\lib\router\index.js:330:12)
at next (C:\Users\devuser\node_modules\express\lib\router\index.js:271:10)
at Immediate. (C:\Users\devuser\node_modules\multer\lib\make-middleware.js:53:37)
at Immediate.immediate._onImmediate (timers.js:440:18)