node.js之文件上传报错:TypeError: Cannot read property '0' of undefined
基于node.js的文件上传
菜鸟教程学习使用node.js,实现文件上传,点击上传文件后却报错:TypeError: Cannot read property '0' of undefined。
(1)index.html代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>node.js 文件上传</title> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> </head> <body> <h3>文件上传</h3> 选择一个文件上传:<br> <form action="http://127.0.0.1:8081/file_upload" method="post" enctype="multipart/from-data"> <input type="file" name="image" size="50"/> <br/> <input type="submit" value="上传文件"/> </form> </body> </html>
(2)server.js的代码如下
var express = require('express'); var app = express(); var fs = require('fs'); var bodyParser = require('body-parser'); var multer = require('multer'); app.use('/public',express.static('public')); app.use(bodyParser.urlencoded({extended:false})); app.use(multer({des:'/tmp/'}).array('image')); app.get('/index.html',function (req,res) { res.sendFile(__dirname + '/' + 'index.html'); }); app.post('/file_upload',function (req,res) { console.log(req.files[0]); var des_file = __dirname + '/' + req.files[0].originalname; fs.readFile(req.files[0].path,function (err,data) { fs.writeFile(des_file,data,function (err) { if(err){ console.log(err); } else { response = { message:'File uploaded successfully', filename:req.files[0].originalname }; } console.log(response); res.end(JSON.stringify(response)); }); }); }); var server = app.listen(8081,function () { var host = server.address().address var port = server.address().port console.log('server running at http://%s:%s',host,port); });
运行server.js,访问index.html,点击上传文件之后跳转路由(/file_upload),显示如下错误:
未解决,求大佬解答?