node.js上传文件

上传思路:
通过multer模块对文件上传,上传后存放到文件夹uploadfile中,然后读取该文件再写入到根目录下

1、index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>文件上传:</h3>
选择一个文件上传: <br />
<form action="/file_upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="上传文件" />
</form>
</body>
</html>
2、upload.js

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 }));

//文件上传模块 multer
app.use(multer({ dest: 'uploadfile/'}).array('file'));

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("应用实例,访问地址为 http://%s:%s", host, port)

})

3、执行node upload.js

在浏览器打开 http://127.0.0.1:8081/index.html
posted @ 2019-05-30 15:07  goodman8  阅读(709)  评论(0编辑  收藏  举报