Slog44_支配vue框架初階項目之博客網站-單頁-客戶端與服務端上傳功能關聯

  • ArthurSlog
  • SLog-44
  • Year·1
  • Guangzhou·China
  • Aug 22th 2018

人們會漸漸愛上壓迫 崇拜那些使他們喪失思考能力的工業產物css


開發環境MacOS(High Sierra 10.13.5)

須要的信息和信息源:

開始編碼

  • 本篇實現 圖片的上傳 和 頭像的修改
  • 上一篇,咱們完成了下面的第一步,如今咱們來完成第二步
  1. 點擊選擇按鈕,彈出本地文件瀏覽框以後,選擇咱們要的圖片,而後點擊確認,鎖定咱們要的圖片
  2. 點擊上傳圖片,將咱們鎖定好的圖片上傳至服務器,顯示上傳的結果,客戶端要作的事情了就到這裏爲止了
  • 參考 vue.js 框架的模版語法 v-on
  • 咱們編寫出一個按鈕,當點擊按鈕的時候,把咱們選擇好的圖片上傳到服務端去:

client/app.htmlhtml

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="./css/style.css">
    <!-- 開發環境版本,包含了有幫助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <title>signin_ArthurSlog</title>
</head>

<body>

    <div id="signup-container">
        <template class="container" v-if="pagestate === '0'">
            <div>This is index's page by ArthurSlog</div>
            <br>
            <button v-on:click="signin_index">Signin</button>
            <br>
            <button v-on:click="signup_index">Signup</button>
        </template>


        <template id="Signin" v-else-if="pagestate === '1'">
            <div>This is signin's page by ArthurSlog</div>
            <p>Singin</p>
            <form id="form1" v-on:submit.prevent="signin">
                <br>
                <div>
                    Account: {{ name_signin }}
                    <br>
                    <input type="text" v-model="name_signin" placeholder="username">
                </div>
                <br>

                <br>
                <div>
                    Password: {{ password_signin }}
                    <br>
                    <input type="text" v-model="password_signin" placeholder="password">
                </div>
                <br>
                <input type="submit" value="登錄">
            </form>
            <br>
            <button v-on:click="return_index">ReturnIndex</button>
        </template>


        <template id="Signup" v-else-if="pagestate === '2'">
            <div>This is signup's page by ArthurSlog</div>
            <p>Singup</p>

            <form id="form2" v-on:submit.prevent="addUser">

                <br>
                <div>
                    Account: {{ name }}
                    <br>
                    <input type="text" v-model="name" placeholder="username">
                </div>
                <br>

                <br>
                <div>
                    Password: {{ password }}
                    <br>
                    <input type="text" v-model="password" placeholder="password">
                </div>
                <br>

                <br>
                <div>
                    Again Password: {{ repassword }}
                    <br>
                    <input type="text" v-model="repassword" placeholder="repassword">
                </div>
                <br>


                <br>
                <div>
                    First Name: {{ firstname }}
                    <br>
                    <input type="text" v-model="firstname" placeholder="firstname">
                </div>
                <br>

                <br>
                <div>
                    Last Name: {{ lastname }}
                    <br>
                    <input type="text" v-model="lastname" placeholder="lastname">
                </div>
                <br>

                <br>
                <div>
                    Birthday: {{ birthday }}
                    <br>
                    <input type="text" v-model="birthday" placeholder="2000/08/08">
                </div>
                <br>

                <br>
                <div>
                    <span>Sex: {{ currentSex }}</span>
                    <br>
                    <input type="radio" id="sex" value="male" v-model="currentSex">
                    <label for="sex">male</label>
                    <br>
                    <input type="radio" id="sex" value="female" v-model="currentSex">
                    <label for="sex">female</label>
                </div>
                <br>

                <br>
                <div>
                    <span>Age: {{ currentAge }}</span>
                    <br>
                    <select v-model="currentAge" id="age">
                        <option disabled value="">Select</option>
                        <option v-for="age in ages">{{ age }}</option>
                    </select>
                </div>
                <br>

                <br>
                <div>
                    Wechart: {{ wechart }}
                    <br>
                    <input type="text" v-model="wechart" placeholder="wechart's name">
                </div>
                <br>

                <br>
                <div>
                    QQ: {{ qq }}
                    <br>
                    <input type="text" v-model="qq" placeholder="12345678">
                </div>
                <br>

                <br>
                <div>
                    Email: {{ email }}
                    <br>
                    <input type="text" v-model="email" placeholder="12345678@qq.com">
                </div>
                <br>

                <br>
                <div>
                    Contury: {{ contury }}
                    <br>
                    <input type="text" v-model="contury" placeholder="China">
                </div>
                <br>

                <br>
                <div>
                    Address: {{ address }}
                    <br>
                    <input type="text" v-model="address" placeholder="Guangzhou">
                </div>
                <br>

                <br>
                <div>
                    Phone: {{ phone }}
                    <br>
                    <input type="text" v-model="phone" placeholder="138********">
                </div>
                <br>

                <br>
                <div>
                    Websize: {{ websize }}
                    <br>
                    <input type="text" v-model="websize" placeholder="xxx.com">
                </div>
                <br>

                <br>
                <div>
                    Github: {{ github }}
                    <br>
                    <input type="text" v-model="github" placeholder="Github's URl">
                </div>
                <br>

                <br>
                <div>
                    Bio: {{ bio }}
                    <br>
                    <input type="text" v-model="bio" placeholder="This is the world~">
                </div>
                <br>

                <br>
                <input type="submit" value="完成註冊">
            </form>

            <button v-on:click="addUser">addUser</button>
            <br>
            <button v-on:click="return_index">ReturnIndex</button>
            <br>
        </template>

        <template id="returnResult" v-else-if="pagestate === '3'">
            <div>
                <img id="ArthurSlog_icon" src="/image/ArthurSlog.png" alt="ArthurSlog_icon" />
            </div>
            <div>
                <div>Uploading {{ image }} files...</div>
                <br>
                <input type="file" v-on:change="filesChange">
                <br>
                <button v-on:click="uploadfiles">uploadfiles</button>
            </div>
            <div id="signinResult">
                <div v-for="(value, key) in commits">
                    {{ key }}: {{ value }}
                </div>
            </div>
        </template>
    </div>
    <script src="./js/signup.js"></script>
</body>

</html>
  • 更新的部分以下:
<br>
<button v-on:click="uploadfiles">uploadfiles</button>
  • 咱們讓 click事件 關聯 uploadfiles函數,也就是說,當點擊按鈕的時候,會觸發 js文件裏的 uploadfiles函數

client/js/signup.jsvue

var host = 'http://127.0.0.1:3000/';

var signup_container = new Vue({
  el: '#signup-container',
  data: {
    name_signin: '',
    password_signin: '',
    name: '',
    password: '',
    repassword: '',
    firstname: '',
    lastname: '',
    birthday: '',
    sexs: ['male', 'female'],
    currentSex: 'male',
    ages: ['1', '2', '3', '4', '5', '6', '7', '8',
      '9', '10', '11', '12', '13', '14', '15', '16', '17', '18'],
    currentAge: '18',
    wechart: '',
    qq: '',
    email: '',
    contury: '',
    address: '',
    phone: '',
    websize: '',
    github: '',
    bio: '',
    commits: null,
    pagestate: '0',
    image: ''
  },
  methods: {
    uploadfiles: function () {
      var xhr = new XMLHttpRequest()
      var fd = new FormData();

      var self = this
      xhr.open('POST', host + 'uploadfiles', true)

      xhr.onload = function () {
        //self.commits = xhr.responseText
        self.commits = xhr.responseText
      }
      fd.append('myFile', this.image);
      xhr.send(fd)
    },
    filesChange: function (event) {
      this.image = event.target.files[0]
    },
    return_index: function () {
      this.pagestate = '0'
    },
    signin_index: function () {
      this.pagestate = '1'
    },
    signup_index: function () {
      this.pagestate = '2'
    },
    signin: function () {
      //當點擊登錄的時候,在頁面上渲染從服務端返回的數據,把其餘的部分隱藏掉
      this.pagestate = '3'

      var xhr = new XMLHttpRequest()

      var self = this
      xhr.open('GET', host + 'signin?' + 'name=' + self.name_signin + '&password=' + self.password_signin, true)

      xhr.onload = function () {
        //self.commits = xhr.responseText
        var myObj = JSON.parse(xhr.responseText);
        self.commits = myObj
      }

      xhr.send()
    },
    addUser: function () {
      //當點擊註冊的時候,在頁面上渲染從服務端返回的數據,把其餘的部分隱藏掉
      this.pagestate = '3'

      var xhr = new XMLHttpRequest()

      /*
      xhr.open('GET', host + 'name=' + this.name + '&password=' + this.password + '&firstname=' + 
      this.firstname + '&lastname=' + this.lastname + '&birthday=' + this.birthday
      + '&sex=' + this.currentSex + '&age=' + this.currentAge + '&wechart=' + this.wechart
      + '&qq=' + this.qq + '&email=' + this.email + '&contury=' + this.contury
      + '&address=' + this.address + '&phone=' + this.phone + '&websize=' + this.websize
      + '&github=' + this.github + '&bio=' + this.bio, true)
      xhr.send()
      */

      var self = this
      xhr.open('GET', host + 'signup?' + 'name=' + self.name + '&password=' + self.password + '&firstname=' +
        self.firstname + '&lastname=' + self.lastname + '&birthday=' + self.birthday
        + '&sex=' + self.currentSex + '&age=' + self.currentAge + '&wechart=' + self.wechart
        + '&qq=' + self.qq + '&email=' + self.email + '&contury=' + self.contury
        + '&address=' + self.address + '&phone=' + self.phone + '&websize=' + self.websize
        + '&github=' + self.github + '&bio=' + self.bio, true)

      xhr.onload = function () {
        self.commits = xhr.responseText
      }

      xhr.send()
    }
  }
})
  • 更新的部分以下:
uploadfiles: function () {
    var xhr = new XMLHttpRequest()
    var fd = new FormData();

    var self = this
    xhr.open('POST', host + 'uploadfiles', true)

    xhr.onload = function () {
    //self.commits = xhr.responseText
    self.commits = xhr.responseText
    }
    fd.append('myFile', this.image);
    xhr.send(fd)
}
  • ok,如今把客戶端的部分解決了,接下來就是 服務端部分 去接收和處理了,咱們更新一下 服務端 的代碼,讓服務端和咱們上面寫的函數關聯起來:

server/index.jsmysql

const serve = require('koa-static');
const Koa = require('koa');
const app = new Koa();
const Router = require('koa-router');
const router = new Router();
const fs = require("fs");
const koaBody = require('koa-body');

// $ GET /package.json
app.use(serve('../client'));

//
router.get('/signin', async (ctx) => {

    var mysql = require('mysql');
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '88888888',
        database: 'my_db'
    });


    connection.connect(function (err) {
        if (err) {
            console.error('error connecting: ' + err.stack);
            return;
        }
        console.log('connected as id ' + connection.threadId);
    });


    var response = {
        "name": ctx.query.name,
        "password": ctx.query.password
    };

    var addSql = 'SELECT * FROM ArthurSlogAccount WHERE AccountName=?';
    var addSqlParams = [response.name];

    var datas = await new Promise((resolve, reject) => {

        connection.query(addSql, addSqlParams, function (err, result) {
            if (err) {
                reject(err);
                console.log('[SELECT ERROR] - ', err.message);
                return;
            }
            if (result[0].Password == response.password) {
                resolve(result[0]);
                console.log('Welcome~ SingIn Successul ^_^' + '\\' + 'Level: ' + result[0].Level + ' Houses: ' + result[0].Houses);
            }
            if (result[0].Password != response.password) {
                reject('SingIn Fault ^_^!');
                console.log('SingIn Fault ^_^!');
            }
        });
    });

    if (datas) {
        ctx.body = datas;
    }

    connection.end();
});

//
router.get('/signup', async (ctx) => {

    var mysql = require('mysql');
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '88888888',
        database: 'my_db'
    });


    connection.connect(function (err) {
        if (err) {
            console.error('error connecting: ' + err.stack);
            return;
        }
        console.log('connected as id ' + connection.threadId);
    });

    var response = {
        "name": ctx.query.name,
        "password": ctx.query.password,
        "firstname": ctx.query.firstname,
        "lastname": ctx.query.lastname,
        "birthday": ctx.query.birthday,
        "sex": ctx.query.sex,
        "age": ctx.query.age,
        "wechart": ctx.query.wechart,
        "qq": ctx.query.qq,
        "email": ctx.query.email,
        "contury": ctx.query.contury,
        "address": ctx.query.address,
        "phone": ctx.query.phone,
        "websize": ctx.query.websize,
        "github": ctx.query.github,
        "bio": ctx.query.bio
    };

    var addSql = 'INSERT INTO ArthurSlogAccount(AccountName, Password, Firstname, Lastname, Birthday, Sex, Age, Wechart, Qq, Email, Contury, Address, Phone, Websize, Github, Bio) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)';
    var addSqlParams = [response.name, response.password, response.firstname, response.lastname, response.birthday, response.sex, response.age, response.wechart, response.qq, response.email, response.contury, response.address, response.phone, response.websize, response.github, response.bio];



    ctx.body = await new Promise((resolve, reject) => {

        connection.query(addSql, addSqlParams, function (err, result) {
            if (err) {
                reject(err);
                console.log('[INSERT ERROR] - ', err.message);
                return;
            }
            resolve('Singup Successful!');
        });
    });

    connection.end();
});

router.post('/uploadfiles', async (ctx) => {

    console.log('客戶端與服務端的 uploadfiles函數 已關聯');

});

app.use(router.routes());

app.listen(3000);

console.log('listening on port 3000');
  • 如今,打開瀏覽器,輸入 127.0.0.1:3000/app.html,點擊 signin 按鈕
  • 輸入帳號:ArthurSlog 密碼:ArthurSlog,點擊登錄
  • 成功登錄以後,點擊 「選擇文件」 按鈕,選擇一張你電腦裏的圖片,而後點擊「打開」
  • 再點擊 uploadfiles 按鈕,觀察 服務端終端,若是終端正常打印出字符串 「客戶端與服務端的 uploadfiles函數 已關聯」,說明客戶端與服務端的 uploadfiles功能 已關聯了起來
  • 至此,咱們完成了 客戶端與服務端之間 uploadfiles功能 的關聯。

歡迎關注個人微信公衆號 ArthurSlog

ArthurSlog

若是你喜歡個人文章 歡迎點贊 留言

謝謝

相關文章
相關標籤/搜索