Hello everyone, I’m Daotin, captain of the front end, want to get more exciting content of the front end, follow me, unlock the new position of the front end growth.

It takes about 8 minutes to read the full text.

The following text:

Today saw someone in the group asked said, there is a business scenario, the user uploaded pictures, pictures to be displayed, does not depend on the back end, refresh the browser will also be displayed, I am stored in the localStorage, if the picture is more than 5MB is more than the maximum storage, there is no way?

First of all, his question reminded me of some operations of image echo after uploading during the development project. Here I will summarize.

1. Rely on the image echo of the back end

After the image is uploaded, the back end will give us the address of the uploaded image. Then we can replace the address with the SRC tag of img. This is a normal operation.

2. Images are displayed at one time without relying on the back end

Not dependent on the back end is that after the image is uploaded, the image preview does not use the back end to return the image address, but the front end through the uploaded image itself display. One-off image output indicates that the image output is displayed after the upload is successful. However, after the page is refreshed, the image is not displayed. This is equivalent to temporarily viewing the uploaded image.

This is a very simple way to do it. There are two ways to do it.

1. Use FileReader to read base64 images

Generally, images will be uploaded to the server in the form of formData. Therefore, for data in formData form, we can use FileReader to read images in Base64 format for display.

The example code is as follows:

    <img src="" alt="">
    <input type="file">
Copy the code
/ / js code
var inputDom = document.querySelector('input');
var imgDom = document.querySelector('img');

inputDom.onchange = function () {

    // Create a formData object and upload it to the server via Ajax
    let formData = new FormData();

    let file = formData.get('iFile');
    console.log('= = >', file);

    // Obtain the file later
    let reader = new FileReader();
    let fileType = file.type;

    // Call reader

    // Reader is finished
    reader.onload = function (e) {
        if(/^image\/[jpeg|png|gif]/.test(fileType)) { imgDom.src = e.target.result; }}}Copy the code

Here is the SRC of img:

2, use createObjectURL function, using object URL display image

The createObjectURL function creates a simple URL string that references any data. Then use this URL as the SRC of img to echo the image.

The code is simple, as follows:

var inputDom = document.querySelector('input');
var imgDom = document.querySelector('img');

inputDom.onchange = function () {
    // Create a temporary URL for the local file
    var objectURL = window.URL.createObjectURL(this.files[0]);
    imgDom.src = src;
Copy the code

Here is the SRC of img:

Reference links:

  • Developer.mozilla.org/zh-CN/docs/…
  • Displays a thumbnail of a user-selected image

3. The image is permanently displayed without relying on the back end

Permanent Image output indicates that the image is still displayed after the page is refreshed.

The current way to do this is to store localStorage locally, but if the image data is too large (more than 10MB, and the current browser localStorage is between 2.5MB and 10MB), then you need a new solution, which is the hero of this article: indexedDB.

In layman’s terms, IndexedDB is a local database provided by the browser that can be created and manipulated by web scripts. IndexedDB allows you to store large amounts of data, provide a lookup interface, and create indexes. These are localStorage does not have.

Before IndexedDB, there was a WebSQL database, but the W3C organization abandoned WebSQL on November 18, 2010. Although both are storage solutions, they do not provide the same functionality. The difference between IndexedDB and WebSQL is that WebSQL is a relational database access system and IndexedDB is a key-value table system.

As to why it was deprecated, see this article: HTML5 indexedDB Front-end Local Storage Database Instance Tutorial

Basic usage of IndexedDB

The basic operation of IndexedDB can refer to ruan Yifeng teacher: Introduction to browser Database IndexedDB tutorial, very detailed, HERE I do not have to repeat it.

Ruan Yifeng teacher wrote the IndexedDB operation tutorial is based on the native IndexedDB API operation, sometimes is more tedious, there are some mature encapsulation js library for us to use?

The answer is yes, and there are plenty of them. With these libraries, we can do IndexedDB faster and easier.

Compatibility with indexedDB

Basically IE10+ all support. Caniuse.com/?search=ind…

IndexedDB encapsulation library recommended

1, Forage (19K star)

LocalForage is a quick, simple JavaScript repository. LocalForage improves the offline experience of Web applications by using asynchronous storage (IndexedDB or WebSQL) using a simple Localstorage-like API. LocalForage automatically uses localStorage in browsers that do not support IndexedDB or WebSQL.

Github: github.com/localForage…

2, PouchDB (14.1K STAR)

PouchDB is an open source JavaScript database inspired by Apache CouchDB designed to work well in browsers. PouchDB was created to help Web developers build applications that work offline as well as online. It enables applications to store data locally when offline and then synchronize it with CouchDB and compatible servers when the application comes back online, so that the user’s data remains synchronized regardless of the next login.

(Temporary offline scenarios that feel like online Office software and do not apply to pure offline scenarios within the meaning of this section)

Github: github.com/pouchdb/pou…

3, Dexie.js (6.6k star)

Dexie.js is the wrapper library for indexedDB.

Github: github.com/dfahlander/…

4, IDB (3.7k STAR)

This is a small library (about 1.09k) that mainly reflects the IndexedDB API, but has some small improvements that have a big impact on usability.

Github: github.com/jakearchiba…


For more exciting content, follow me for more front-end technology and personal growth related content, I’m sure interesting people will meet!

It is said that people who click “like” will be lucky enough to get a promotion and a raise a month later