chapter 14 html5 web storage, file api, web...

23
Web Programming Networking Laboratory 1/23 Sungkyunkwan University Copyright 2000-2012 Networking Laboratory Copyright 2000-2018 Networking Laboratory Chapter 14 HTML5 Web Storage, File API, Web Socket Prepared by J. Jung and H. Choo

Upload: others

Post on 25-Sep-2020

18 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 14 HTML5 Web Storage, File API, Web Socketmonet.skku.edu/.../2018/08/...File-API-Web-Socket.pdf · Understanding the syntax of WebSocket API Web Programming Networking Laboratory

Web Programming Networking Laboratory 1/23

Sungkyunkwan University

Copyright 2000-2012 Networking LaboratoryCopyright 2000-2018 Networking Laboratory

Chapter 14

HTML5 Web Storage,

File API, Web Socket

Prepared by J. Jung and H. Choo

Page 2: Chapter 14 HTML5 Web Storage, File API, Web Socketmonet.skku.edu/.../2018/08/...File-API-Web-Socket.pdf · Understanding the syntax of WebSocket API Web Programming Networking Laboratory

Web Programming Networking Laboratory 2/23

Web Storage

Web storage is a mechanism for storing data on client computers.

Web storage is safer and faster than cookies.

Web storage can store about 5MB.

Data is stored as a pair of (key, value).

Page 3: Chapter 14 HTML5 Web Storage, File API, Web Socketmonet.skku.edu/.../2018/08/...File-API-Web-Socket.pdf · Understanding the syntax of WebSocket API Web Programming Networking Laboratory

Web Programming Networking Laboratory 3/23

Local Storage & Session Storage

Local Storage

Store data with no expiration date.

Different domains cannot access each other’s local storage.

In “google.com”, user can not access “naver.com” local storage.

Session Storage

Data is stored separately for each session (one window).

When the session ends, the data disappears.

Page 4: Chapter 14 HTML5 Web Storage, File API, Web Socketmonet.skku.edu/.../2018/08/...File-API-Web-Socket.pdf · Understanding the syntax of WebSocket API Web Programming Networking Laboratory

Web Programming Networking Laboratory 4/23

Local Storage Example (1/3)Page Visits Count

<!DOCTYPE html><html><head></head><body>

<p>페이지방문횟수 : <span id="count"></span>

</p><script>

if (!localStorage.pageLoadCount) // pageLoadCount가존재하지않을경우localStorage.pageLoadCount = 0; // 초기화

localStorage.pageLoadCount = parseInt(localStorage.pageLoadCount) + 1;document.getElementById('count').textContent = localStorage.pageLoadCount;

</script></body></html>

Understanding the syntax and life cycle of local storage

Page 5: Chapter 14 HTML5 Web Storage, File API, Web Socketmonet.skku.edu/.../2018/08/...File-API-Web-Socket.pdf · Understanding the syntax of WebSocket API Web Programming Networking Laboratory

Web Programming Networking Laboratory 5/23

Local Storage Example (2/3)Button Clicks Count (1/2)

<!DOCTYPE html><html><head></head><body>

<p><button onclick="incrementCounter()" type="button">눌러보세요!</button>

</p><div id="target"></div>

Understanding the syntax and life cycle of local storage

Page 6: Chapter 14 HTML5 Web Storage, File API, Web Socketmonet.skku.edu/.../2018/08/...File-API-Web-Socket.pdf · Understanding the syntax of WebSocket API Web Programming Networking Laboratory

Web Programming Networking Laboratory 6/23

Local Storage Example (3/3)Button Clicks Count (2/2)

<script>function incrementCounter() {

// localStorage를지원하는지확인if (('localStorage' in window) && window['localStorage'] !== null) {

if (localStorage.count) {localStorage.count++;

}else {

localStorage.count = 1;}document.getElementById("target").innerHTML =

localStorage.count + “번클릭하였습니다.”;}else {

document.getElementById("target").innerHTML =“Local Storage Unavailable”;

}}

</script></body></html>

Understanding the syntax and life cycle of local storage

Page 7: Chapter 14 HTML5 Web Storage, File API, Web Socketmonet.skku.edu/.../2018/08/...File-API-Web-Socket.pdf · Understanding the syntax of WebSocket API Web Programming Networking Laboratory

Web Programming Networking Laboratory 7/23

Session Storage Example (1/2)Button Clicks Count (1/2)

<!DOCTYPE html><html><head></head><body>

<p><button onclick="incrementCounter()" type="button">눌러보세요!</button>

</p><div id="target"></div>

Understanding the syntax and life cycle of session storage

Page 8: Chapter 14 HTML5 Web Storage, File API, Web Socketmonet.skku.edu/.../2018/08/...File-API-Web-Socket.pdf · Understanding the syntax of WebSocket API Web Programming Networking Laboratory

Web Programming Networking Laboratory 8/23

Session Storage Example (2/2)Button Clicks Count (2/2)

<script>function incrementCounter() {

// sessionStorage를지원하는지확인if (('sessionStorage' in window) && window['sessionStorage'] !== null) {

if (sessionStorage.count) {sessionStorage.count++;

}else {

sessionStorage.count = 1;}document.getElementById("target").innerHTML =

sessionStorage.count + “번클릭하였습니다.”;}else {

document.getElementById("target").innerHTML =“Session Storage Unavailable”;

}}

</script></body></html>

Understanding the syntax and life cycle of session storage

Page 9: Chapter 14 HTML5 Web Storage, File API, Web Socketmonet.skku.edu/.../2018/08/...File-API-Web-Socket.pdf · Understanding the syntax of WebSocket API Web Programming Networking Laboratory

Web Programming Networking Laboratory 9/23

Various Syntax of Web Storage (1/2)

Save

localStorage.setItem(“nick”, “name”);

localStorage.nick = “name”;

localStorage[“nick”] = “name”;

Load

var name = localStorage.getItem(“nick”);

var name = localStorage.nick;

var name = localStorage[“nick”];

Erase

localStorage.removeItem(“nick”);

delete localStorage.nick;

delete localStorage[“nick”];

Page 10: Chapter 14 HTML5 Web Storage, File API, Web Socketmonet.skku.edu/.../2018/08/...File-API-Web-Socket.pdf · Understanding the syntax of WebSocket API Web Programming Networking Laboratory

Web Programming Networking Laboratory 10/23

Various Syntax of Web Storage (2/2)

Available Check

if (window.localStorage) { … }

Clear

localStorage.clear();

Load All Data of LocalStorage

for (var i=0; i<localStorage.length; i++) {

var key = localStorage.key(i);

var value = localStorage[key];

}

for (var key in localStorage) {

var value = localStorage[key];

}

Page 11: Chapter 14 HTML5 Web Storage, File API, Web Socketmonet.skku.edu/.../2018/08/...File-API-Web-Socket.pdf · Understanding the syntax of WebSocket API Web Programming Networking Laboratory

Web Programming Networking Laboratory 11/23

Web Storage Example (1/2)Simple Notepad (1/2)

<!DOCTYPE html><html lang="ko"><head><meta charset="utf-8" /><title>Simple Notepad</title>

</head><body onload="loadMemo()"><h2>Simple Notepad</h2><textarea id="txtBox" onKeyUp="saveMemo();" cols="50" rows="5"></textarea><br /><input type="button" value="Clear" onClick="clearMemo();" /><p id="info" style="display: none;">Autosave Completed.</P>

</body>

Understanding the syntax and life cycle of local and session storage

Page 12: Chapter 14 HTML5 Web Storage, File API, Web Socketmonet.skku.edu/.../2018/08/...File-API-Web-Socket.pdf · Understanding the syntax of WebSocket API Web Programming Networking Laboratory

Web Programming Networking Laboratory 12/23

Web Storage Example (2/2)Simple Notepad (2/2)

<script type="text/javascript">function saveMemo() {info = document.getElementById("info");info.style.display = "block"; // 보이도록변경localStorage.setItem(“memo”, msg.value);

};function loadMemo() {msg = document.getElementById("txtBox");msg.value = localStorage.getItem("memo");

};function clearMemo() {msg.value = ""; // 작성된메모지우기localStorage.clear(); // 저장된메모지우기info.style.display = "none"; // 보이지않도록변경

};</script>

</html>

Understanding the syntax and life cycle of local and session storage

Page 13: Chapter 14 HTML5 Web Storage, File API, Web Socketmonet.skku.edu/.../2018/08/...File-API-Web-Socket.pdf · Understanding the syntax of WebSocket API Web Programming Networking Laboratory

Web Programming Networking Laboratory 13/23

File API

An API that allows a web browser to read local files on your computer.

Act like a normal program running on a PC (web application).

The most typical application of the file API is that

the user selects a file and sends it to a remote server.

Objects used in the File API are File and FileReader.

The File object represents file data obtained from the local file system.

The FileReader object is an object that provides methods

for accessing data in a file through event handling.

Page 14: Chapter 14 HTML5 Web Storage, File API, Web Socketmonet.skku.edu/.../2018/08/...File-API-Web-Socket.pdf · Understanding the syntax of WebSocket API Web Programming Networking Laboratory

Web Programming Networking Laboratory 14/23

File API Example (1/6)Read Text File (1/2)

<!DOCTYPE html><html><head>

<title>HTML File API </title></head><body>

<input type="file" id="input" name="input"><button id="readfile" onclick="readFile()">파일읽기</button><br /><textarea id="result" rows="6" cols="60"></textarea>

</body>

Understanding the syntax of File API

Page 15: Chapter 14 HTML5 Web Storage, File API, Web Socketmonet.skku.edu/.../2018/08/...File-API-Web-Socket.pdf · Understanding the syntax of WebSocket API Web Programming Networking Laboratory

Web Programming Networking Laboratory 15/23

File API Example (2/6)Read Text File (2/2)

<script>function readFile() {

// File API를지원하는지확인if (!window.File || !window.FileReader) {

alert('File API Unavailable');return;

}// file input에입력된 file 목록을수집var files = document.getElementById('input').files;if (!files.length) { // 파일개수가 0개인경우

alert(‘Select a file’);return;

}var file = files[0];var reader = new FileReader();reader.onload = function () { // 읽기동작이완료됐을때

document.getElementById('result').value = reader.result;};reader.readAsText(file, "euc-kr");

}</script>

</html>

Understanding the syntax of File API

Page 16: Chapter 14 HTML5 Web Storage, File API, Web Socketmonet.skku.edu/.../2018/08/...File-API-Web-Socket.pdf · Understanding the syntax of WebSocket API Web Programming Networking Laboratory

Web Programming Networking Laboratory 16/23

File API Example (3/6)Read File Information (1/2)

<!DOCTYPE html><html><head>

<title>HTML File API </title></head><body>

<input type="file" id="input" name="input"><button id="readfile" onclick="readFile()">파일읽기</button><br /><textarea id="result" rows="6" cols="60"></textarea>

</body>

Understanding the syntax of File API

Page 17: Chapter 14 HTML5 Web Storage, File API, Web Socketmonet.skku.edu/.../2018/08/...File-API-Web-Socket.pdf · Understanding the syntax of WebSocket API Web Programming Networking Laboratory

Web Programming Networking Laboratory 17/23

File API Example (4/6)Read File Information (2/2)

<script>function readFile() {

var files = document.getElementById('input').files;output = "";for (var i = 0, f; f = files[i]; i++) { // 입력된파일개수만큼반복

output += f.name + "\n"; /* f.name - Filename */output += f.type + "\n"; /* f.type - File Type */output += f.size + "bytes\n"; /* f.size - File Size */output += f.lastModifiedDate + "\n"; /* f.lastModifiedDate */

}document.getElementById('result').value = output;

}</script>

</html>

Understanding the syntax of File API

Page 18: Chapter 14 HTML5 Web Storage, File API, Web Socketmonet.skku.edu/.../2018/08/...File-API-Web-Socket.pdf · Understanding the syntax of WebSocket API Web Programming Networking Laboratory

Web Programming Networking Laboratory 18/23

File API Example (5/6)Read Image File (1/2)

<!DOCTYPE html><html lang="ko"><head><meta charset="utf-8" /><title>Load Image</title>

</head><body><h3>Load Image</h3><img id="preview" src="" width="300" height="300" alt="Preview"><br /><input type="file" id="fileUpload" accept="image/*">

</body>

Understanding the syntax of File API

Page 19: Chapter 14 HTML5 Web Storage, File API, Web Socketmonet.skku.edu/.../2018/08/...File-API-Web-Socket.pdf · Understanding the syntax of WebSocket API Web Programming Networking Laboratory

Web Programming Networking Laboratory 19/23

File API Example (6/6)Read Image File (2/2)

<script type="text/javascript">var file = document.querySelector('#fileUpload');file.onchange = function() { // 파일입력란에변화가생긴경우

var image = file.files[0];var reader = new FileReader();reader.readAsDataURL(image); // readAsText와다른함수reader.onload = function() {document.querySelector('#preview').src = reader.result;

};};

</script></html>

Understanding the syntax of File API

Page 20: Chapter 14 HTML5 Web Storage, File API, Web Socketmonet.skku.edu/.../2018/08/...File-API-Web-Socket.pdf · Understanding the syntax of WebSocket API Web Programming Networking Laboratory

Web Programming Networking Laboratory 20/23

Web Socket

Web Socket is a next-generation two-way communication technology

for Web Applications

The application can take advantage of all the features provided by

TCP/IP by avoiding the frustrating constraints of HTTP.

Request upgrade to web socket

Okay, you are now web socket

BrowserServer

I’ll stop now.

Page 21: Chapter 14 HTML5 Web Storage, File API, Web Socketmonet.skku.edu/.../2018/08/...File-API-Web-Socket.pdf · Understanding the syntax of WebSocket API Web Programming Networking Laboratory

Web Programming Networking Laboratory 21/23

Web Socket Example (1/2)Echo Server Communication (1/2)

<!DOCTYPE HTML><html><head><meta charset="utf-8" /><title>Websocket</title>

</head><body><button onclick="openWebSocket()">웹소켓연결</button><button onclick=“quitWebSocket()”>웹소켓연결종료</button><br /><input type=“text” id=“data” /><button onclick=“send()”>데이터송신</button><br />에코서버로부터받은데이터 :<output id="result"></output>

</body>

Understanding the syntax of WebSocket API

Page 22: Chapter 14 HTML5 Web Storage, File API, Web Socketmonet.skku.edu/.../2018/08/...File-API-Web-Socket.pdf · Understanding the syntax of WebSocket API Web Programming Networking Laboratory

Web Programming Networking Laboratory 22/23

Web Socket Example (2/2)Echo Server Communication (2/2)

<script type="text/javascript">var ws;function openWebSocket() {

if ("WebSocket" in window) { // WebSocket API를지원하는지확인ws = new WebSocket("ws://echo.websocket.org"); // WebSocket연결ws.onopen = function() { // 연결된경우

alert("WebSocket Open Success");};ws.onmessage = function(evt) { // 메시지를수신한경우

var msg = evt.data;document.getElementById("result").innerHTML = msg;

};ws.onclose = function() { // 연결이종료된경우

alert("WebSocket Close");};

} else {alert("WebSocket unavailable");

}}function quitWebSocket() { ws.close(); }function send() { ws.send(document.getElementById("data").value); }

</script></html>

Understanding the syntax of WebSocket API

Page 23: Chapter 14 HTML5 Web Storage, File API, Web Socketmonet.skku.edu/.../2018/08/...File-API-Web-Socket.pdf · Understanding the syntax of WebSocket API Web Programming Networking Laboratory

Web Programming Networking Laboratory 23/23

Q & A