博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
5. 文件上传下载 与 db数据库
阅读量:5302 次
发布时间:2019-06-14

本文共 8606 字,大约阅读时间需要 28 分钟。

文件上传

formidable

multer

npm i formidable multer

如何使用见:

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
无标题文档

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: 
, 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  默认的配置  以后启动 mogodmongod --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环境下运行

导入数据:

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

使用方法:


mongodb浏览器的可视化

adminMongo


mongoose:

mongodb/mongoose

DOM 文档对象模型

ODM 对象文档模型
npm i mongoose


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);//创建数据  行 documentvar 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 will be removed in a future version. To use the new parser, pass option { useNewUrlParser: 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 will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.连接已经建立

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

转载于:https://www.cnblogs.com/zhongchao666/p/9346926.html

你可能感兴趣的文章
spring mvc 页面form提示语
查看>>
ps aux 状态介绍
查看>>
二级指针内存模型
查看>>
bzoj千题计划140:bzoj4519: [Cqoi2016]不同的最小割
查看>>
二进制学习 wsample01a.exe
查看>>
[数据结构与算法]二叉排序(搜索)树实现
查看>>
Query Designer:Hierarchy层级显示
查看>>
SQL SERVER数据库开发之存储过程应用(转载)
查看>>
第十三章----面向对象(综合)
查看>>
条码、QRCode生成组件 zxing 使用范例
查看>>
Python基础(一)
查看>>
设计出色的数据产品
查看>>
Leetcode 377. Combination Sum IV
查看>>
【STL源码剖析读书笔记】自己实现priority_queue之MyPriorityQueue
查看>>
SSH框架总结(框架分析+环境搭建+实例源码下载)
查看>>
java多线程的实现的两种方法
查看>>
Spring Security(07)——缓存UserDetails
查看>>
jsp分页完善版
查看>>
Android开发之修改Manifest中meta-data的数据
查看>>
【清北前紧急补课5】辣鸡奶酪
查看>>