// 1. 生成package,json文件
npm init
// 2. 安装express 生成 node_modules 文件夹
cnpm install express
用 express 上传文件:
html 部分
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>文件上传</title>
</head>
<body>
<h3>文件上传:</h3>
选择一个文件上传: <br />
<form action="http://localhost:8081/file_upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" /><br />
<input type="submit" value="上传文件" />
</form>
</body>
</html>
要点:
(1) enctype的三种类型:
① enctype="application/x-www-form-urlencoded"
用于上传哈希值(eg: ?a=12&b=5&c=8);
② enctype="multipart/form-data"
用于上传文件;
③ enctype="text-plain"
用于上传文本;
(2) <input type="file" name="file" />
此处的input,必须要有name属性(后台选择谁上传);
uploadfiles.js
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const multer = require('multer');
const pathLib = require('path');
const app = express();
// body-parser 用于解析post数据 application/x-www.form-urlencoded
app.use(bodyParser.urlencoded({extended: false}));
// multer 用于解析post文件 multipart/form-data
// var objMulter = multer({dest: './dist'}).array('file');
// 或者 var objMulter = multer({dest: './dist'}).any();
app.use(multer({dest: './dist'}).array('file')); //此处的array('file')对应html部分的name
// app.use(objMulter );
app.post('/file_upload', function(req, res){
console.log(req.files[0]);
fs.readFile(req.files[0].path, function(err, data){
if(err){
console.log('Error');
}else{
var dir_file = __dirname + '/' + req.files[0].originalname
// console.log(dir_file);
fs.writeFile(dir_file, data, function(err){
var obj = {
msg: 'upload success',
filename: req.files[0].originalname
}
console.log(obj);
res.send(JSON.stringify(obj));
})
}
})
})
var server = app.listen(8081, function(){
var host = server.address().address;
var port = server.address().port;
console.log('Server is running at http://localhost:8081');
})
要点:
① body-parser 用于解析post数据 application/x-www.form-urlencoded
② multer 用于解析post文件 multipart/form-data
如有错误,请各位留言指点!
网友评论