const Koa = require("koa");
const static = require("koa-static");
const Router = require("koa-router");
const koaBody = require("koa-body");
// 引入 fs模块处理文件
const fs = require("fs");
const mysql2 = require("mysql2");
let app = new Koa();
let router = new Router();
app.use(static(__dirname+"/static"));
const connection = mysql2.createConnection({
host:"localhost",
user:"root",
password:"123321",
database:"js04"
})
app.use(koaBody({
multipart:true //允许文件上传
}))
//首页
router.get("/",ctx=>{
// ctx.body = "something...";
ctx.redirect("/login.html");
})
router.post("/upload",async ctx=>{
// 获取的文件数据ctx.request.files
// console.log(ctx.request.files.img.path);
// 转存文件地址
fs.writeFileSync("./static/img/uploads/"+ctx.request.files.img.name,fs.readFileSync(ctx.request.files.img.path));
// 将文件路径数据存入到数据库;
let imgUrl = "/img/uploads/"+ctx.request.files.img.name;
let imgName = ctx.request.files.img.name;
// 通过cookies 判断当前登录用户;
let uid = ctx.cookies.get("uid") || 1; //默认1 如果用户没注册 登录者显示默认的数据
let [rows] = await connection.promise().query("INSERT INTO photo(imgUrl,imgName,uid) VALUES (?,?,?)",[imgUrl,imgName,uid]);
let resData; //插入 数据库表单的 值 路径 名 uid 编号
if(rows.affectedRows>0){ // 添加成功
resData = {
info:"添加成功",
status:1
}
}else{
resData = {
info:"添加失败",
status:0
}
}
ctx.body = resData;
})
//获取图片数据做对应呈现;(区分用户)
router.get("/getPhotoData",async ctx=>{
let uid = ctx.cookies.get("uid") || 1; //通过cookies储存的uid编号来判断 是谁登陆的
let [rows] = await connection.promise().query("SELECT * FROM photo WHERE uid=?",[uid]);
console.log(rows); // 返回对应 uid 编号对应所有内容
ctx.body = rows; //返回到页面
})
// 接收页面发送的数据 并且去数据库 查询
router.all("/checkUser",async ctx=>{
// 认证是否登录;
// console.log(ctx.request.body);
let {username,pwd} = ctx.request.body; //request.body接收后自动转成对象
console.log(username,pwd);
let [rows] = await connection.promise().query("SELECT * FROM users WHERE username=? AND pwd=?",[username,pwd]);
// console.log(rows);
let resData; //返回的数据
if(rows.length>0){
// 如果是对的 将id存入服务端的cookie;uid是名称 rows[0].id谁登陆存储谁的id值 时效性
ctx.cookies.set('uid', rows[0].id, { maxAge: 3600*1000*24*7 });
resData = { //如果是对的 返回的数据
info:"用户名密码正确", //
status:1 // 判断用户名和密码后返回状态码,返回前段状态1 再去判断
}
}else{ // 如果数错的返回的 数据
resData = {
info:"用户名或者密码错误",
status:0
}
}
ctx.body = resData; // 如果数错 返回当前页面
})
app.use(router.routes());
app.listen(8686);
登录界面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="css/login.css" />
<title>Document</title>
</head>
<body>
<div class="loginContainer">
<h1>登录</h1>
<form action="/checkUser" method="post" onsubmit="return false;">姓名:
<input class="inputStyle" id="username" type="text" name="username" /><br />密码:
<input class="inputStyle" id="pwd" type="password" name="pwd" /><br />
<input class="loginStyle" id="sub" type="submit" value="登录" />
</form>
</div>
</body>
<script>
// document.querySelector("#username")
document.querySelector("#sub").onclick = function () {
let username = document.querySelector("#username").value; //1获取账号密码
let pwd = document.querySelector("#pwd").value;
// console.log(username,pwd);
let xhr = new XMLHttpRequest();
xhr.open("post", "/checkUser", true); //路径checkUser
xhr.setRequestHeader("content-type","application/json");
xhr.onload = function () {
// console.log(JSON.parse(xhr.responseText));
let res = JSON.parse(xhr.responseText);
if(res.status==1){ // 如果状态是1 说明用户名密码正确 进入主页
window.location.href = "/photo.html";
}else{ //否则返回用户提示
alert(res.info);
}
};
let data = {
username,
pwd
}
xhr.send(JSON.stringify(data)); // 2发送账号密码 转字符串 路径checkUser
}
</script>
</html>
主界面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="css/photo.css">
</head>
<body>
<!-- 展示相关 -->
<div class="container">
<div class="photoHeader">
<div class="imgContainer">
<img class="photoName" src="img/1.jpg" />
</div>
<div class="btnContainer">
<span class="photoTitle">相册名称</span>
<button class="mybtn">上传照片</button>
</div>
</div>
<div class="photoContainer">
<div class="photoItem">
<img src="img/Home.png" />
<span>
home
</span>
</div>
</div>
</div>
<!-- 上传相关 -->
<div class="masking">
<div class="addPhotoContainer"></div>
<div class="addController">
<h3 class="addTitle">上传照片-普通上传(H5)<span class="close">╳</span></h3>
<div class="photoTitles">
<span class="uploadTo">上传到</span>
<div class="photoSelect">
<img class="showPhoto" src="/img/1.jpg" />
相册名称
</div>
</div>
<!-- 上传按钮 -->
<div class="showContainer">
<div class="uploadContainer">
<span class="fileinput-button">
<span>上传图片</span>
<input class="imgFile" type="file" name="" multiple="multiple" />
</span>
<span class="hint">
按住Ctrl可多选
</span>
</div>
</div>
<!-- 显示待上传图片 -->
<div class="loadContainer">
<div class="wantUpload">
<!-- <div class="uploadPhotoItem">
<span class="myProgress">
<span class="plan"></span>
30%
</span>
<img src="img/1.jpg" />
<span class="pictureName">
home
</span>
</div> -->
</div>
<div class="addStyle">
<span class="fileinput-add">
<span></span>
<input class="imgFile-add" type="file" multiple="multiple" />
</span>
</div>
<!-- 开始上传按钮 -->
<div class="bottomStyle">
<span class="uploadBtn">开始上传</span>
</div>
</div>
</div>
</div>
</body>
<script>
// 存放将要上传的图片对象;
let uploadArr = [];
let num = 0;
document.querySelector(".close").onclick = function () {
document.querySelector(".masking").style.display = "none";
}
document.querySelector(".mybtn").onclick = function () {
document.querySelector(".masking").style.display = "block";
}
// 首次添加
document.querySelector(".imgFile").onchange = function () {
document.querySelector(".uploadContainer").style.display = "none";
document.querySelector(".loadContainer").style.display = "block";
console.log(this.files);
// this.files.fo
// Array.from 等同于[...this.files].forEach()
Array.from(this.files).forEach(file => {
let uploadItme = new UploadItem(file); //file传到工具类 实例化出对象
uploadArr.push(uploadItme); // 添加到数据
uploadItme.createHtml(); // 渲染显示到页面
})
}
//大加号 继续添加
document.querySelector(".imgFile-add").onchange = function () {
Array.from(this.files).forEach(file => {
let uploadItme = new UploadItem(file);
uploadItme.createHtml();
uploadArr.push(uploadItme);
})
}
// 点击上传 首次添加和继续添加只是添加到小页面上并没有 上传服务器
document.querySelector(".uploadBtn").onclick = function () {
console.log(uploadArr);
async function queue() {
for (let i = 0; i < uploadArr.length; i++) {
await uploadArr[i].uploadImg(); //每次点击上传按钮 每上传一张图片都去调用
num++; //传一张 加1 上传图片uploadImg()方法
}
if (num >= uploadArr.length) { //当num等于 数组长度时 说明上传完成
console.log("上传全部完成");
document.querySelector(".masking").style.display = "none"; //关闭那个小页面
initHtml(); // 上传全部全成后 重新加载页面
}
}
queue();
}
// 工具 类
class UploadItem {
constructor(file) {
this.file = file;
this.ele = "";
}
createHtml() {
let fileReader = new FileReader();
fileReader.readAsDataURL(this.file);
let _this = this;
fileReader.onload = function () {
// console.log(this.result);
let uploadPhotoItem = document.createElement("div");
uploadPhotoItem.classList.add("uploadPhotoItem");
uploadPhotoItem.innerHTML = `<span class="myProgress">
<span class="plan"></span>
<span class="exchange"> 30%</span>
</span>
<img src="${this.result}" />
<span class="pictureName">
${_this.file.name}
</span>`;
document.querySelector(".wantUpload").appendChild(uploadPhotoItem);
_this.ele = uploadPhotoItem;
}
}
// 上传图片
uploadImg() { //异步ajax发送
return new Promise(resolve => {
let xhr = new XMLHttpRequest();
xhr.open("post", "/upload", true);
let form = new FormData();
form.append("img", this.file);
xhr.upload.onprogress = (evt) => {
// console.log(evt.loaded,evt.total);
console.log(this.ele);
this.ele.querySelector(".myProgress").style.display = "block";
// console.log(Math.round( evt.loaded/evt.total *100)+ "%");
let percent = Math.round(evt.loaded / evt.total * 100) + "%";
this.ele.querySelector(".plan").style.width = percent;
this.ele.querySelector(".exchange").innerHTML = percent;
if (evt.loaded >= evt.total) {
// 上传完成;
resolve();
}
}
xhr.send(form);
})
}
}
// 上来就执行的ajax功能 去服务端getPhotoData
function initHtml() {
let xhr = new XMLHttpRequest();
xhr.open("get", "/getPhotoData", true);
xhr.onload = function () { //getPhotoData 路由通过判断id编号来 返回相对应的数据
// console.log(xhr.responseText);
let res = JSON.parse(xhr.responseText);
let photoHtml = "";
console.log(res); //输出看一下
res.forEach(item => { //看用 forEach 还是forIn
photoHtml += ` <div class="photoItem">
<img src="${item.imgUrl}" />
<span>
${item.imgName}
</span>
</div>`;
}) //渲染到页面
document.querySelector(".photoContainer").innerHTML = photoHtml;
}
xhr.send();
}
initHtml();
</script>
</html>
ajax qq空间上传相册
最新推荐文章于 2020-04-30 16:04:49 发布