nodejs --- 上传文件并保存到磁盘

2021-07-02 03:06

阅读:625

YPE html>

标签:htm   磁盘   复习   size   har   class   next   parse   host   

先复习下整个请求的过程

const express = require(express);
const static = require(express-static);
const cookieParser = require(cookie-parser);
const cookieSession = require(cookie-session);
const bodyParser = require(body-parser);
const multer = require(multer);
const ejs = require(ejs);
const jade = require(jade);

const server = express();

server.listen(8999);

// 解析cookie
server.use(cookieParser(dfadfasdfa));

// 解析session
let arr = [];
for(let i = 0; i 100000; i++) {
    arr.push(key_ + Math.random());
}

server.use(cookieSession({name: jason_name, keys: arr, maxAge: 20*3600*1000}));

// post数据
server.use(bodyParser.urlencoded({extended: false}));
server.use(multer({dest: ./www/upload}).any());

// 用户请求
server.use(/, (req, res, next) => {
    console.log(req.query, req.body, req.files, req.cookie, req.session);
});

server.use(static(./www));

测试下能不能上传

const express = require(express);
const bodyParser = require(body-parser);
const multer = require(multer);
// fs 可以用来添加上传文件的扩展名(重命名)
const fs = require(fs);
const pathLib = require(path);

const server = express();


// 创建一个上传文件对象
// let objMulter = multer({dest: ‘./www/upload‘});

server.use(bodyParser.urlencoded({extended: false}));
// server.use(objMulter.any());

server.post(/, (req, res) => {
    console.log(req.body==>,req.body);
    // 当请求是 enctype=application/x-www-form-urlencoded 
    // req.body==> { f1: ‘mmexport1485905379121.jpg‘ }
    // 当请求是 multertype/form-type
    // req.body==> {}
    // console.log(‘req.files==>‘, req.files);
});

server.listen(8999);

上传的表单文件

"en">"UTF-8">
    文件上传
"http://localhost:8999" method="post" enctype="application/x-www-form-urlencoded"> 文件: "file" name="f1">
"submit" value="上传">
这是因为body-parser 只能处理application/x-www-form-urlencoded
 
文件上传 需要使用 multer 模块 用来处理 multipart/form-data
const express = require(express);
const bodyParser = require(body-parser);
const multer = require(multer);
// fs 可以用来添加上传文件的扩展名(重命名)
const fs = require(fs);
const pathLib = require(path);

const server = express();


// 创建一个上传文件对象
let objMulter = multer({dest: ./www/upload});

// server.use(bodyParser.urlencoded({extended: false}));
server.use(objMulter.any());

server.post(/, (req, res) => {
    // console.log(‘req.body==>‘,req.body);
    console.log(req.files==>, req.files);
     // req.files==> [ { fieldname: ‘f1‘,
     //    originalname: ‘IMG_20170125_212945.jpg‘,
     //    encoding: ‘7bit‘,
     //    mimetype: ‘image/jpeg‘,
     //    destination: ‘./www/upload‘,
     //    filename: ‘fa0b73da8bdbcb36e9480e9869c0a2b7‘,
     //    path: ‘www\\upload\\fa0b73da8bdbcb36e9480e9869c0a2b7‘,
     //    size: 226929 } ]
     
});

server.listen(8999);

这个时候你会发现文件上传了,但是文件名没有扩展名

fs中重名的函数rename
 
fs.rename(‘a.txt‘, ‘b.txt‘, (err) => {
     console.log(err);
});
 
获取扩展名的插件  path  可以小小的测试下 这个node中的path插件
const path = require(path);

let str = c:\\wamp\\www\\a.html;

let obj = path.parse(str);

console.log(obj);

// {
//   root: ‘c:\\‘,
//   dir: ‘c:\\wamp\\www‘,
//   base: ‘a.html‘,
//   ext: ‘.html‘,
//   name: ‘a‘
// }
// base   文件名部分
// ext     扩展名部分
// dir      文件路径(目录)
// name  文件名(不包含扩展名)
 
然后讲path插件添加进文件
const express = require(express);
const bodyParser = require(body-parser);
const multer = require(multer);
// fs 可以用来添加上传文件的扩展名(重命名)
const fs = require(fs);
const pathLib = require(path);

const server = express();


// 创建一个上传文件对象
let objMulter = multer({dest: ./www/upload});

// server.use(bodyParser.urlencoded({extended: false}));
server.use(objMulter.any());

server.post(/, (req, res) => {
    // console.log(‘req.body==>‘,req.body);
    console.log(req.files==>, req.files);
     // req.files==> [ { fieldname: ‘f1‘,
     //    originalname: ‘IMG_20170125_212945.jpg‘,
     //    encoding: ‘7bit‘,
     //    mimetype: ‘image/jpeg‘,
     //    destination: ‘./www/upload‘,
     //    filename: ‘fa0b73da8bdbcb36e9480e9869c0a2b7‘,
     //    path: ‘www\\upload\\fa0b73da8bdbcb36e9480e9869c0a2b7‘,
     //    size: 226929 } ]
    //1.获取原始的扩展名  2.重命名临时文件
    let newName = req.files[0].path + pathLib.parse(req.files[0].originalname).ext
    fs.rename(req.files[0].path, newName, (err) => {
        if(err) {
            console.log(重命名失败);
        }else {
            console.log(命名成功);
        }
    });
});

//     req.files==> [ { fieldname: ‘f1‘,
//     originalname: ‘IMG_20170125_212945.jpg‘,
//     encoding: ‘7bit‘,
//     mimetype: ‘image/jpeg‘,
//     destination: ‘./www/upload‘,
//     filename: ‘bb031c31a1016648703a0d54cc93f674‘,
//     path: ‘www\\upload\\bb031c31a1016648703a0d54cc93f674‘,
//     size: 226929 } ]
// 命名成功

server.listen(8999);
 
到此,文件成功的保存到磁盘中,并且大小一致
 
总结: 
     body-parser      解析post数据     application/x-www-form-urlencoded
     multer               解析post文件      multipart/form-data
 
let  obj = multer({dest: ‘上传路径‘});
 
server.use(obj.any());
 
server.use( (req, res) => {
     req.files[0].originalname
     req.files[0].path
});
 
fs.rename(老名字, 新名字, (err) => {
 
});
 

nodejs --- 上传文件并保存到磁盘

标签:htm   磁盘   复习   size   har   class   next   parse   host   

原文地址:http://www.cnblogs.com/jasonwang2y60/p/7129075.html


评论


亲,登录后才可以留言!