5. 文件上传下载 与 db数据库

文件上传

formidable
multer

npm i formidable multer

如何使用见: https://www.npmjs.com/

util.inspect 自己查

文件上传:表单必须有2个东西

1、enctyp="multipart/form-data"
2、method="post"

文件下载:

res.download(__filename);

formidable

server1.js
var http = require("http");
var formidable = require("formidable");
var fs = require("fs");
var path = require("path");

http.createServer(function(req,res){
	
	console.log(req.url);
	if(req.url == "/upload"){
		var form = new formidable.IncomingForm();
		form.uploadDir = "upload";
		form.parse(req, function(err, fields, files) {
			 
			console.log(fields, files);
			
			var oFile = files.f1;
			
			var oldPath = oFile.path;
			
			var newName = oldPath + oFile.name;
			fs.rename(oldPath,newName,function(err){
				res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});//设置response编码为utf-8
				if(err){
					res.end("上传失败");
				} else {
					res.end("上传成功");
				}	
			});
			
			
		});
	}
	
}).listen(9000);
form.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>

<body>
<form action="http://localhost:9000/upload" enctype="multipart/form-data" method="post">
	<input type="text" name="user" value="aaa" /> <br /><br />
	<input type="file" name="f1" value="" /> <br /><br />
	<input type="submit"/>
</form>
</body>
</html>

res:

$ node server
/upload
{ user: 'aaa' } { f1:
   File {
     domain: null,
     _events: {},
     _eventsCount: 0,
     _maxListeners: undefined,
     size: 5,
     path: 'upload\\upload_df6a908be04c7a08d5406784cfbcb468',
     name: 'test.txt',
     type: 'text/plain',
     hash: null,
     lastModifiedDate: 2018-07-13T12:55:25.753Z,
     _writeStream:
      WriteStream {
        _writableState: [Object],
        writable: false,
        domain: null,
        _events: {},
        _eventsCount: 0,
        _maxListeners: undefined,
        path: 'upload\\upload_df6a908be04c7a08d5406784cfbcb468',
        fd: null,
        flags: 'w',
        mode: 438,
        start: undefined,
        autoClose: true,
        pos: undefined,
        bytesWritten: 5,
        closed: true } } }

image

server.js
var express = require("express");
var multer = require("multer");
var fs = require("fs");

var app = express();

app.listen(9000);

app.use(express.static("www"));
app.use(express.urlencoded({extended:false}));

//文件上传中间件

var multerMiddleware = multer().any();
app.use(multerMiddleware);

app.use("/upload",function(req,res){
	
	console.log(req.files);
	
	var oFile = req.files[0];
	
	var path = "upload/"+ oFile.originalname;
	var buf = oFile.buffer;
	fs.writeFileSync(path,buf);
	
});

res:

$ node server2
[ { fieldname: 'f1',
    originalname: 'test.txt',
    encoding: '7bit',
    mimetype: 'text/plain',
    buffer: <Buffer 36 36 36 36 36>,
    size: 5 } ]

image

文件下载download
var express = require("express");

var app = express();

app.listen(9000);
 
app.use("/download",function(req,res){
	 
	res.download(__filename);//下载自己
});

res:
image

db数据库

mysql与 mongodb

1.mysql

npm i mysql 驱动

连接数据库

var db = mysql.createConnection({
	host,user,password,database
});

操作数据库:
db.query(sql,fn(err,data){...});
关闭数据库:
db.end(); 不是close();

//查询

select * from user_table;
select * from user_table where username="aaa" and password="123";

插入

insert into user_table(username,password) values("aaa","123");


2.mongodb
     mysql            mongodb —— json
 
    关系型数据库     非关系型数据库

库   database         database

表    table          collection集合

行    row            document文档

列    col            field属性

安装目录: C:\Program Files\MongoDB\Server\3.3\bin

mongod 服务器端

mongo 客户端

配置环境变量:

;C:\Program Files\MongoDB\Server\3.3\bin

执行:

mongod --dbpath C:\data\db  默认的配置  以后启动 mogod

mongod --dbpath C:\mongoData 每次启动服务器必须带上完整路径

常用命令:

show dbs显示所有数据 —— 只显示有数据的库名称 show databases

db 查看用户当前所在的数据库

use 切换数据库、创建数据库

插入数据

db.user.insert({a:1}); 包括创建表 和 插入数据
db.user.insertOne( { x: 1 } );

db.user.find();

db.user.find({x:1});

select * from user_table where x="1"

use 20180713

db.user_table.insert({username:"aaa",password:"123",age:1});
db.user_table.insert({username:"aaa1",password:"123",age:18});
db.user_table.insert({username:"aaa2",password:"123",age:30});
db.user_table.insert({username:"aaa3",password:"123",age:60});

db.user_table.find({},{username:0/1,"_id":0});

select password from user_table

db.getCollection("user_table").find();

db.user_table.find().pretty() 美化json

show collections 查询当前库里面所有的表

db.user_table.find( { age: { $gt: 18 } } ,{"_id":0}) >
db.user_table.find( { age: { $gte: 18 } } ,{"_id":0}) >=
db.user_table.find( { age: { $lt: 18 } } ,{"_id":0}) <
db.user_table.find( { age: { $lte: 18 } } ,{"_id":0}) <=

db.user_table.find( {age:{ $gt: 18, $lt: 60 }},{"_id":0}) >18 <60

db.user_table.find({},{"_id":0}).sort( { age: -1 } ); 1 -1

1 :降序 desc
-1:升序 asc

db.user_table.find({},{"_id":0}).limit(2)
db.user_table.find({},{"_id":0}).limit(2).skip(0)

limit(pageSize).skip(beginIndex);

beginIndex = pageSize*(pageNo-1)

pageSize 2条

pageNo   beginIndex
  1         0
  2         2
  3         4
  4         6

11条数据 每页2条 一共几页? Math.ceil(total/pageSize);

db.user_table.count();


db.collection.insert()

db.collection.insertOne() 同 insert
db.collection.insertMany([ <document 1> , <document 2>, ... ])

db.user_table.insertMany([ 
			{username:"xxx1",password"xxx1",age:1},
			{username:"xxx2",password"xxx2",age:2},
			{username:"xxx3",password"xxx3",age:3}
]);
db.user_table.insertMany([
			{username:"xxx1",password:"xxx1",age:1},
			{username:"xxx2",password:"xxx2",age:2},
			{username:"xxx3",password:"xxx3",age:3}
]);
db.user_table.insert([
			{username:"xxx11",password:"xxx1",age:1},
			{username:"xxx22",password:"xxx2",age:2},
			{username:"xxx33",password:"xxx3",age:3}
]);

update
$set:修改或者添加
db.user_table.update(
   { username: "aaa" },
   {
     $set: {username: "AAA", password: "AAA",age: 100}
   }
)

db.user_table.update( { username: "AAA" }, { $unset: { password: 1 } } )
$unset 删除属性


db.user_table.find({},{"_id":0}); 

db.user_table.update(
   { username: "aaa1" },
   { $set: { username : "AAA1" } },
   { multi: true}  可以修改多条数据 默认是false
)

db.user_table.updateOne(
    { username: "aaa3" },
    { $set: { username : "AAA3" } }
);
db.user_table.updateMany(
    { username: "aaa2" },
    { $set: { username : "AAA2" } }
);

删除 没有delete 用remove

db.user_table.deleteOne( { "_id" : ObjectId("5b48548b86ffbcc901fc4ac2") } );

db.user_table.deleteOne( { "age" : {$gte:1}} );

db.user_table.deleteMany( { "age" : {$gte:1}} );

db.user_table.remove( { "age" : {$gte:1}} );

db.user_table.remove( { "age" : {$gte:1}},{justOne:true} );

justOne:true 只删除一条 默认false删除所有


注意:必须在cmd环境下运行

https://stackoverflow.com/questions/47282119/mongo-export-syntaxerror-missing-before-statement-shell114

导入数据:

mongoimport --db 20180713 --collection user_table --drop --file xxx.txt

导出数据

mongoexport --db 20180713 --collection user_table --out xxx.txt

xxx.txt 
{username:"xxx1",password:"xxx1",age:1}
{username:"xxx2",password:"xxx2",age:2}
{username:"xxx3",password:"xxx3",age:3}

mongodb&& node

npm i mongodb

使用方法:https://www.npmjs.com/package/mongodb


mongodb浏览器的可视化
adminMongo https://github.com/mrvautin/adminMongo


mongoose:

mongodb/mongoose

DOM 文档对象模型
ODM 对象文档模型
npm i mongoose

https://www.npmjs.com/package/mongoose

http://mongoosejs.com/


db.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/20180716');

//定义表结构的数据类型
var userSchema = new Schema({
	user:String,
	pass:String
});
//定义表 表结构都会带s,只能有一个s    控制台查询:db.user_tables.find();
var UserModel = mongoose.model('user_table', userSchema);

//创建数据  行 document
var oUser = new UserModel({user:"bbb"});
oUser.pass = "123";

//db.user_table.insert(document);
//插入
oUser.save(function (err, result) {
  	console.log(err, result);
	//查询
	//find
	UserModel.find(function (err, data) {
		console.log(err, data);
	})
});

res:

$ node db.js
(node:9996) DeprecationWarning: current URL string parser is deprecated, and wil
l be removed in a future version. To use the new parser, pass option { useNewUrl
Parser: true } to MongoClient.connect.
null { _id: 5b4c780013c2a1270cd6c0fd,
  user: 'bbb',
  pass: '123',
  __v: 0 }
null [ { _id: 5b4c76c859b0432a1c4e0626,
    user: 'bbb',
    pass: '123',
    __v: 0 },
  { _id: 5b4c780013c2a1270cd6c0fd,
    user: 'bbb',
    pass: '123',
    __v: 0 } ]

db2.js

连接成功测试

/*var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/716');


var db = mongoose.connection;
db.on('error', function() {
  console.log("连接失败");
});
db.once('open', function() {
  console.log("连接已经建立");
});*/
//或者
/*var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/20180716',function(err) {
  	if(err){
		console.log("连接失败");
	} else {
		console.log("连接已经建立");
	}
});*/

res:

$ node db2
(node:11436) DeprecationWarning: current URL string parser is deprecated, and wi
ll be removed in a future version. To use the new parser, pass option { useNewUr
lParser: true } to MongoClient.connect.
连接已经建立

心中那自由的世界,如此的清澈高远!

posted @ 2018-07-21 15:53  飞刀还问情  阅读(515)  评论(0编辑  收藏  举报