Geolocation API


                        navigator.geolocation.getCurrentPosition(
                            function (position) { ... },
                            function (error) { ... },
                            options
                        );

                        const options = {
                            enableHighAccuracy: true,
                            maximumAge: 50000,
                            timeout: 10000
                        };
                    

                        const watcherId = navigator.geolocation.watchPosition(...);

                        navigator.geolocation.clearWatch(watcherId);
                    

Coordinates


                        {
                            coords: {
                                accuracy: 45,
                                altitude: null,
                                altitudeAccuracy: null,
                                heading: null,
                                latitude: 56.783005499999994,
                                longitude: 60.54139849999999,
                                speed: null
                            },
                            timestamp: 1459788138892
                        }
                    

Geolocation API

  • GPS - Global Positioning System
  • Google's Geolocation Service Chrome, Firefox, Opera
  • Microsoft Location Service Internet Explorer, Edge

File APIs

Для чего?

  • Доступ к файлам из файловой системы
  • Получение контента файла без отправки на сервер
  • Работа с файлами как с бинарными данными
  • Blob — file-like объект, позволяет работать с бинарными данными
  • File — основан на Blob
  • FileList — набор объектов типа File
  • FileReader — позволяет осуществлять чтение объектов типа Blob или File и получать доступ к их контенту

                        if (window.Blob && window.File &&
                            window.FileList && window.FileReader) {
                          // File APIs полностью поддерживаются
                        } else {
                          // File APIs поддерживаются не полностью
                        }
                    

Blob


                        const blobA = new Blob(['abc', 'def'], options);
                        const blobB = new Blob([blobA, 'abc'], options);
                        const blobC = new Blob([blobA, blobB], options);

                        const options = {
                            type: 'plain/text',
                            endings: 'native' // transparent
                        };
                    

Blob


                        blob.size // Размер в байтах
                        blob.type // MIME-type

                        blob.slice(start, end, contentType);
                        blob.close();
                    

Blob URLs


                        const blob = new Blob(['abc'], { type: 'plain/text' });

                        const url = URL.createObjectURL(blob);
                        // blob:d3958f5c-0777-0845-9dcf-2cb28783acaf

                        URL.revokeObjectURL(url);
                    

Пример: Скачивание файла

                        
                            <a download="text.txt">Скачать</a>
                        
                    

Пример: Скачивание файла

                        
                            const link = document.getElementById('link');
                            const textarea = document.getElementById('textarea');

                            textarea.addEventListener('change', function (event) {
                                const text = event.target.value;
                                const blob = new Blob([text], { type: 'plain/text' });

                                link.href = URL.createObjectURL(blob);
                            });
                        
                    
Скачать

Создание файлов различных форматов

Создание файлов различных форматов: jsPDF

                        
                            const doc = new jsPDF()

                            doc.text(20, 20, 'Hello world!');
                            doc.text(20, 30, 'This is client-side Javascript');

                            doc.addPage();

                            doc.text(20, 20, 'Do you like that?');
                        
                    

jsPDF

Создание файлов различных форматов: jsZip

                        
                            const zip = new JSZip();
                            const img = zip.folder('images');

                            zip.file('Hello.txt', 'Hello World\n');
                            img.file('smile.gif', imgData, { base64: true });

                            zip
                                .generateAsync({ type: 'blob' })
                                .then(function(content) {
                                    // see FileSaver.js
                                    saveAs(content, 'example.zip');
                                });
                        
                    
jsZip

Загрузка файлов


                        <input type="file" multiple />
                        <input type="file" multiple accept="application/pdf" />
                        <input type="file" multiple accept="image/png,image/jpeg" />
                        <input type="file" multiple accept="image/*" />
                        <input type="file" multiple accept="video/*" />
                        <input type="file" multiple accept="audio/*" />
                    

                        const input = document.getElementById('input');

                        input.addEventListener('change', function () {
                            const files = input.files; // FileList

                            files.length;
                            files[0];
                            files.item(0);
                        });
                    

Drag and Drop


                        <div id="drop-zone"></div>
                        <div id="names"></div>
                    

                        const dropZone = document.getElementById('drop-zone');
                        const names = document.getElementById('names');

                        dropZone.addEventListener('dragover', function (event) {
                            event.preventDefault();
                            event.dataTransfer.dropEffect = 'copy';
                        });
                    

Drag and Drop


                        dropZone.addEventListener('drop', function (event) {
                            event.preventDefault();

                            const files = event.dataTransfer.files;
                            const output = [];

                            for (let i = 0; i < files.length; i++) {
                                output.push('<li>' + files[i].name + '</li>');
                            }

                            names.innerHTML = '<ol>' + output.join('') + '</ol>';
                        });
                    
Подробнее про Drag and Drop
Перетащите файлы

File


                        {
                            lastModified: 1461053555000,
                            lastModifiedDate: 'Date 2016-04-18T09:23:08.000Z',
                            name: 'img.png',
                            size: 8057,
                            type: 'image/png'
                        }
                    

Чтение файла

                        
                            const reader = new FileReader();

                            reader.readAsArrayBuffer(file);
                            reader.readAsBinaryString(file);
                            reader.readAsDataURL(file);
                            reader.readAsText(file);
                            reader.abort();
                        
                    

Чтение файла


                        reader.onerror
                        reader.onloadstart
                        reader.onloadend  // даже в случаее неудачной загрузки
                        reader.onload     // только в случае успеха
                        reader.onprogress

                        reader.error
                        reader.readyState // EMPTY - 0, LOADING - 1, DONE - 2
                        reader.result
                    

Чтение файла


                        <input type="file" id="input" accept=".csv"/>
                        <div id="table"></div>
                    

                        const input = document.getElementById('input');
                        const table = document.getElementById('table');

                        input.addEventListener('change', function () {
                            const csv = input.files[0];
                            const reader = new FileReader();

                            reader.addEventListener('load', function () {
                                table.innerHTML = csvToHtml(reader.result);
                            });

                            reader.readAsText(csv);
                        });
                    

Полезные ссылки

File APIs на w3.org
File APIs на MDN
Чтение файлов в JavaScript с помощью API файлов Создание редактора изображений в браузере