發布任務~
一、path模塊
二、url模塊
三、formidable包
一、path模塊
path 模塊提供用于處理文件路徑和目錄路徑的實用工具
const paths = require('path');
let dir = 'D:/node/';
// 將碎片化路徑拼接在一起,規范化生成的路徑
path.join(dir, './public'); // D:\node\public
let extStr = '/index.html';
// path的擴展名
path.extname(extStr); // .html
二、url模塊
用于處理與解析 URL
實例化URL
new URL(input)
input: 要解析的輸入URL
let url = '/';
let appUrl = new URL('http://localhost:3002' + decodeURIComponent(req.url));
// URL {
// href: 'http://localhost:3002/',
// origin: 'http://localhost:3002',
// protocol: 'http:',
// username: '',
// password: '',
// host: 'localhost:3002',
// hostname: 'localhost',
// port: '3002',
// pathname: '/',
// search: '',
// searchParams: URLSearchParams {},
// 獲取表示URL查詢參數的URLSearchParams對象
// 通過get(key) 可獲取value
// hash: ''
// }
實戰: 使用formidable實現上傳圖片
客戶端:
<body>
<input type="file" id="file">
<div id="img-containers"></div>
</body>
let file = document.getElementById('file');
let imgContainer = document.getElementById('img-containers');
file.addEventListener('change', uploadFile);
function uploadFile() {
// 實例化formData
let form = new FormData();
// 實例化讀取文件
let fileReader = new FileReader();
fileReader.onload = function () {
let img = document.createElement('img');
img.src = fileReader.result;
// 顯示圖片
img.onload = function () {
imgContainer.appendChild(img);
}
}
fileReader.readAsDataURL(this.files[0]);
// 存入單張圖片至formData中
form.set('file', this.files[0]);
// 可存入多張 (Array)
// form.append('file', this.files[0]);
filePost('/upload', form, (data) => {
console.log(data);
})
}
// post 傳輸文件(formData格式)
function filePost(url, form, callback) {
let xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
callback(xhr.responseText);
}
}
xhr.send(form);
}
服務端
引入基本依賴
const http = require('http');
const fs = require('fs');
const paths = require('path');
let dir = 'D:/node/'
console.log(paths.join(dir, './public'));
const { URL } = require('url');
// 上傳文件的第三方包
const formidable = require('formidable');
// 以流的方式讀取文件,當訪問/作為首頁返回
const readStreamIndex = fs.createReadStream('./public/html/index.html');
搭建服務及創建路由接口
http.createServer((req, res) => {
// 將url轉為url對象
let appUrl = new URL('http://localhost:3002' + decodeURIComponent(req.url));
// 返回首頁
if (req.method === 'GET' && appUrl.pathname === '/') {
readStreamIndex.pipe(res);
}
if (req.method === 'POST' && appUrl.pathname === '/upload') {
// 創建一個新的的正在進入的表單
var form = new formidable.IncomingForm();
// 指定文件保存路徑
form.uploadDir = './public/uploads';
// 解析文件
form.parse(req, function (err, fields, files) {
if (err) res.end(JSON.stringify(err));
// 修改文件名
var oldPath = paths.join(__dirname, files['file'].path);
// 以時間戳命名 以免 文件重名
var comment = new Date() * 1 + '';
var newPath = paths.join(__dirname, './public/uploads', comment + files['file'].name);
// 保存在用戶信息里面
fields.imgSrc = newPath;
// 文件重命名
fs.rename(oldPath, newPath, function (err) {
res.writeHead(200, { 'Content-type': 'text/plain; charset=UTF-8' });
var result = err ? '上傳失敗' : '上傳成功';
if (err) res.end(result);
// 存儲圖片信息
fs.writeFile(__dirname + '/imgInfor/' + comment + '.json', JSON.stringify(fields), function (err) {
res.writeHead(200, { 'Content-type': 'text/plain; charset=UTF-8' });
var result = err ? '上傳失敗' : '上傳成功';
res.end(result);
});
});
});
}
}).listen(3002, (err) => {
if (err) throw err;
console.log('listen 3002');
});