1. 程式人生 > >nodejs學習文件day3——express框架整合

nodejs學習文件day3——express框架整合

express:

  1. 主體
  2. cookie、session
  3. 資料
  4. 模板引擎

body-parser    解析post資料  enctype="application/x-www-form-urlencoded"

server.use(bodyParser.urlencode());

    req.body

multer            解析post檔案  enctype="multipart/form-data"

var obj=multer({dest:'upload/'});

server.use(obj.any());

server.use(functuon(req,res){

     req.files[0].originalname;

     req.files[0].path

})

把副檔名加上

                    //'upload/aksjdhakjhdsad'+'.txt'

                    //'upload/aksjdhakjhdsad.txt'

 var newName=file.path+pathLib.parse(file.originalname).ext;

fs.rename

----------------------------------------------------------------------------------------------

簡易上傳檔案伺服器

server_file.js

const express=require('express');
const bodyParser=require('body-parser');
const multer=require('multer');
const fs=require('fs');  //用其rename函式修改上傳上來的檔名字尾
const pathLib=require('path');  //獲取檔案路徑以及檔案字尾名


var objMulter=multer({dest:'./www/upload'});
var server=express();

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


server.post('/',function(req,res){
	//新檔名
	//'./www/upload/akjdhaisuhdkjqawedhkajsd' + '.xxx'
	var newName=req.files[0].path+  pathLib.parse(req.files[0].originalname).ext;

	fs.rename(req.files[0].path,newName,function(err){
		if(err)
			res.send('上傳失敗!');
		else
			res.send('上傳成功!');
	});
	//1.獲取原始副檔名

	//2.改字尾
});

server.listen(8082);

unload.html

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title></title>
</head>
<body>
	<form action="http://localhost:8082/" method="post" enctype="multipart/form-data">
		檔案:<input type="file" name="f1"><br>
		<input type="submit" value="上傳">
	</form>
</body>
</html>

-------------------------------------------------------------------------------------------------