JS file transfer, 10 HTML file upload skills, web user experience design improvement guide, strange knowledge — bitmask | si no technology weekly

Time:2021-7-30

Today, I share the knowledge points to improve work happiness. I hope you don’t miss these good articles~

1、JS files Base64, file, blob and arraybuffer are transferred to each other

Binary conversion

  1. File object to Base64
let reader = new FileReader();
 reader.readAsDataURL(file[0])
 console.log(reader)
  1. Convert Base64 to blob upload
function dataURItoBlob(dataURI) {  
    var byteString = atob(dataURI.split(',')[1]);  
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];  
    var ab = new ArrayBuffer(byteString.length);  
    var ia = new Uint8Array(ab);  
    for (var i = 0; i < byteString.length; i++) {  
        ia[i] = byteString.charCodeAt(i);  
    }  
    return new Blob([ab], {type: mimeString});  
}
  1. Convert blob to arraybuffer
let blob = new Blob([1,2,3,4])
let reader = new FileReader();
reader.onload = function(result) {
    console.log(result);
}
reader.readAsArrayBuffer(blob);
  1. Convert buffer to blob
let blob = new Blob([buffer])
  1. Base64 to file
const   base64ConvertFile  =  function  ( urlData,   filename)  { //  64 RPM file
  if (typeof urlData != 'string') {
    This. $toast ("urldata is not a string")
    return;
  }
  var arr = urlData.split(',')
  var type = arr[0].match(/:(.*?);/)[1]
  var fileExt = type.split('/')[1]
  var bstr = atob(arr[1])
  var n = bstr.length
  var u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], 'filename.' + fileExt, {
    type: type
  });
}

2、10 HTML file upload skills

The upload file function can be said to be a frequent requirement of the project. Upload your resume to social media and post it everywhere. In this article, we will discuss 10 usages supported by HTML file upload, hoping to be useful to you.

1. Single file upload

We can specify the input type as file to use the file upload function in the web application.

<input type="file" id="file-uploader">

Input filter provides a button to upload one or more files. By default, it uploads a single file using the operating system’s native file browser. After successful upload, the file API   Makes it possible to read the file object using simple JS code. To read the file object, we need to listen   Change event.

First, get the file upload instance through ID:

const fileUploader = document.getElementById('file-uploader');

Then add a change   Event listener to read the file object after uploading. We get the uploaded file information from the event.target.files attribute:

fileUploader.addEventListener('change', (event) => {
  const files = event.target.files;
  console.log('files', files);
});

Observe the output results in the console. Here, focus on the filelist array and file object, which has all metadata information about the uploaded file.

JS file transfer, 10 HTML file upload skills, web user experience design improvement guide, strange knowledge -- bitmask | si no technology weekly

If you are a little excited and want to be cheap, you can play with codepen, address:

https://codepen.io/atapas/pen…

2. Multi file upload

If we want to upload multiple files, we need to add the multiple attribute on the tag:

<input type="file" id="file-uploader" multiple />

Now, we can upload multiple files. Based on the previous examples, select multiple files to upload and observe the changes on the console:

JS file transfer, 10 HTML file upload skills, web user experience design improvement guide, strange knowledge -- bitmask | si no technology weekly

If you are a little excited and want to be cheap, you can play with codepen, address:

https://codepen.io/atapas/pen…

3. Understand file metadata

Whenever we upload a file, the file object has metadata information, such as file name, size, last update time, type, and so on. This information is useful for further verification and special processing.

const fileUploader = document.getElementById('file-uploader');

//   Listen more   change   File and read metadata
fileUploader.addEventListener('change', (event) => {
  //   Get file list array
  const files = event.target.files;
  //   Traverse and get metadata
  for (const file of files) {
    const name = file.name;
    const type = file.type ? file.type: 'NA';
    const size = file.size;
    const lastModified = file.lastModified;
    console.log({ file, name, type, size, lastModified });
  }
});

The following is the output of single file upload:

JS file transfer, 10 HTML file upload skills, web user experience design improvement guide, strange knowledge -- bitmask | si no technology weekly

If you are a little excited and want to be cheap, you can play with codepen, address:

https://codepen.io/atapas/pen…

4. Understand   accept   attribute

We can use the accept attribute to limit the type of file to be uploaded. If the file format to be uploaded is. JPG,. PNG, you can do this:

<input type="file" id="file-uploader" accept=".jpg, .png" multiple>

In the above code, only files with. JPG and. PNG suffixes can be selected.

If you are a little excited and want to be cheap, you can play with codepen, address:

https://codepen.io/atapas/pen…

5. Contents of management documents

After uploading the file successfully, the file content is displayed. From the user’s point of view, if there is no preview after uploading, it is very strange and considerate.

We can use the FileReader object to convert files to binary strings. Then add load   Event listener to get binary strings when files are uploaded successfully.

//   FileReader   example
const reader = new FileReader();
fileUploader.addEventListener('change', (event) => {
  const files = event.target.files;
  const file = files[0];
  reader.readAsDataURL(file);
  reader.addEventListener('load', (event) => {
    const img = document.createElement('img');
    imageGrid.appendChild(img);
    img.src = event.target.result;
    img.alt = file.name;
  });
});

If you are a little excited and want to be cheap, you can play with codepen, address:

https://codepen.io/atapas/pen…

There are five tips to share at the end of the article, namely:

6. Verify file size

  1. Display file upload progress
  2. How to upload a directory?
  3. Drag upload
  4. Processing files using objecturl

You can click the title link to browse all the skills in the original article~

3、Incomplete guide to front-end good practice

This article should be called the web user experience design improvement guide.

A web page, an app, wants to be used by others, that is, the so-called good user experience. I think it may include but not limited to:

  • Rapid opening speed
  • Bright UI design
  • Cool animation
  • Rich personalization
  • Convenient operation B
  • Intimate details
  • Attention to the disabled, good accessibility

The so-called user experience design, in fact, is a relatively virtual concept. It is a design means adhering to the user-centered idea and aiming at the needs of users. The design process focuses on the user as the center. The concept of user experience has entered the whole process from the earliest stage of development and runs through it.

Good user experience design is the result of joint efforts in every link of the product.

In addition to some problems that are difficult to achieve overnight, this paper will start with page display, interaction details and accessibility, and list some useful experiences accumulated in the actual development process. Through this article, you will gain:

  1. Learn how some small details affect the user experience
  2. Learn how to improve the user experience of the page with as few development changes as possible
  3. Learn some excellent interaction design details
  4. Understand the meaning of basic accessibility and page accessibility
  5. Understand the basic ways to improve page accessibility

4、13 top-level free WYSIWYG text editor tools

CKEditor

Ckeditor has more than 10 years of development experience. You can rest assured of the quality of this text editor. It supports more than 70 languages. I think it’s a good choice for your website. It can also run on many different browsers and work well with most front-end frameworks, such as reat, Vue, angular… You can use CDN to embed it directly into your HTML page. At present, it has two versions of ckeditor4 and ckeditor5 running in parallel. You will choose your own editor according to different purposes.

JS file transfer, 10 HTML file upload skills, web user experience design improvement guide, strange knowledge -- bitmask | si no technology weekly

Trumbowyg

Trumbowyg is a code editor optimized for HTML5. It supports most popular browsers, such as IE9 +, Firefox, chrome, etc. As far as I know, it contains all the tools for text editing. It is only 20KB. It is lightweight and will help your website run more smoothly. In addition, it also has other support plug-ins to help you work better, such as inserting emoticons, supporting languages in other countries, adding sounds, inserting special characters

JS file transfer, 10 HTML file upload skills, web user experience design improvement guide, strange knowledge -- bitmask | si no technology weekly

TinyMCE

TinyMCE 5 is an editor that allows you to edit, add or delete some content in this program flexibly. In addition to the basic editor, I found that it also provides a lot of support, better user experience, such as adding comments, testing and checking paths, providing high-quality icons and interfaces, and checking spelling content… However, this is also its weakness, because if you want to use high-level tools, you must pay about $25 a month.

JS file transfer, 10 HTML file upload skills, web user experience design improvement guide, strange knowledge -- bitmask | si no technology weekly

Quill

Quill is an open source editor, so it can be used for all types of commercial or non-commercial websites. It has many functions, such as adding links, images, videos or adding code snippets… My favorite thing about quill is its simple setting and display, which can be displayed on all modern and responsive web browsers on multi device screens, as well as a detailed description of common problems using it.

JS file transfer, 10 HTML file upload skills, web user experience design improvement guide, strange knowledge -- bitmask | si no technology weekly

Trix

Trix is an open source editor that allows you to easily write messages, comments, posts… On the web and be used by well programmed tablets. If you only need to create the functions required for content, trix is also a good choice.

JS file transfer, 10 HTML file upload skills, web user experience design improvement guide, strange knowledge -- bitmask | si no technology weekly

Jodit Editor 3

Jodit Editor 3 is an open source GitHub editor written in pure typescript without any other libraries. It allows you to set it up in many ways, such as through NPM, using CDN. What I like about it is that in addition to the detailed description, there is a program that allows us to freely choose which tools to attach to jodit editor through code.

JS file transfer, 10 HTML file upload skills, web user experience design improvement guide, strange knowledge -- bitmask | si no technology weekly

Summernote

Summernote is an open source editor on GitHub and has won more than 9K stars. It is designed through the bootstrap framework and has all the functions required to create content on your website. You only need to download its source files CSS and JS, and the bootstrap framework (also supports versions 3 and 4) can serve your website.

JS file transfer, 10 HTML file upload skills, web user experience design improvement guide, strange knowledge -- bitmask | si no technology weekly

Editor.js

Editor.js is an open source block editor. It will not use HTML tags like ordinary editors and output the content in the form of JSON, making it easier to manage. It also supports plug-ins through the use of APIs. Thanks to this, any developer can contribute more interesting and useful plug-ins to the program.

JS file transfer, 10 HTML file upload skills, web user experience design improvement guide, strange knowledge -- bitmask | si no technology weekly

MediumEditor

Mediumeditor is the built-in open source editor of medium for people’s blogs. It contains only the basic utilities required by the editor, so it is only about 28KB, which will help your website to be optimized. At the same time, if we want to add other functions, in order to optimize editing, mediumeditor also provides additional external utilities, which are updated regularly.

JS file transfer, 10 HTML file upload skills, web user experience design improvement guide, strange knowledge -- bitmask | si no technology weekly

Wysihtml

Wysihtml is an open source editor built by the voog team. It is fully functional, can help you easily edit text, and supports device images in most modern screen browsers. There are many tools I like very much. It automatically converts inappropriate HTML tag rate, automatically analyzes content from word, PDF, and displays content as HTML

JS file transfer, 10 HTML file upload skills, web user experience design improvement guide, strange knowledge -- bitmask | si no technology weekly

ContentTools

Content tools is a built-in open source editor that helps you easily edit HTML content in one way. It provides various utilities for editing content, and you can easily add the message Institute and other utilities to the program (see the offline API section). I also found articles on how to set, add or delete functions in programs… Are very detailed.

JS file transfer, 10 HTML file upload skills, web user experience design improvement guide, strange knowledge -- bitmask | si no technology weekly

Froala

Froala is an editor that can be easily set up for a website and allows you to open a wide range of functions according to your intended use. Because it is written in pure JavaScript, you can use it in most modern front-end frameworks today. It also provides many useful tools, as well as editing images, adding or editing videos, adding icons, management panel, etc. However, if you want to use the tool for commercial purposes, you must purchase a license.

JS file transfer, 10 HTML file upload skills, web user experience design improvement guide, strange knowledge -- bitmask | si no technology weekly

Redactor

Redactor is a full-featured editor with exquisite and simple design. I want to support many plug-ins for more than 9 years. In addition, it has extremely detailed examples of every common problem encountered by programmers in the process of using the program. However, it also has a disadvantage that you must purchase a license when you use it for commercial purposes.

JS file transfer, 10 HTML file upload skills, web user experience design improvement guide, strange knowledge -- bitmask | si no technology weekly

5、Strange knowledge – bit mask

Suppose we have a permission system that records the permission opening of a user through JSON (let’s assume that the permission set is curd):

const permission = {
  create: false,
  update: false,
  read: true,
  delete: false,
}

If we write false as 0 and true as 1, the permisson object can be abbreviated as   0b0010。

const permission = {
  create: false,
  update: false,
  read: true,
  delete: false,
}
//   From left to right   create,   update,   read,   delete   Corresponding value
const permissionBinary = 0b0010

For the permission set of JSON objects, if we want to view or modify some permissions of the user, we only need to operate through ordinary objects such as permission.craete. So how should we view or modify binary permission sets? Then we began to use the strange knowledge – bit mask.

bitmask

First, explain the noun, what is “bit mask”.

Bitmask is a combination of “bit” and “Mask” Bit “refers to the binary bit in the binary data, while” Mask “refers to a string of binary digits used for bit-by-bit operation with the target data. Combined, it means “using a string of binary digits (mask) to operate another string of binary digits”.

After understanding the role of bit mask, we can operate on the binary number of permission set through it.

1. Query whether the user has a certain permission

The binary number of known user permission sets is permissionbinary = 0b0010. If I want to know if the user exists   update   This permission can be given a bit mask first   mask = 0b1。

JS file transfer, 10 HTML file upload skills, web user experience design improvement guide, strange knowledge -- bitmask | si no technology weekly

Since update is in the third item on the right, you only need to move the bit mask two bits to the left and fill the remaining positions with 0. Finally, the result can be obtained by bitwise sum with the binary number of permission set.

JS file transfer, 10 HTML file upload skills, web user experience design improvement guide, strange knowledge -- bitmask | si no technology weekly

The final result is   0b0000, using boolean()   Function can get the result of false, that is, the user’s update permission is false.

//   From left to right   create,   update,   read,   delete   Corresponding value
const permissionBinary = 0b0010
//   because   update   It is in the third bit to the right, so you only need to move the mask 2 bits to the left
const mask = 0b1 << 2
const result = permissionBinary & mask
Boolean(result) // false

2. Modify a user’s permission

When we understand how to use the bit mask to query permissions, it is easy to modify the corresponding permissions. It is just a bit operation. Suppose or   update   Permissions, if I want to change it to   True, we can do this:

JS file transfer, 10 HTML file upload skills, web user experience design improvement guide, strange knowledge -- bitmask | si no technology weekly

Just change bitwise and to bitwise XOR. The code is as follows:

//   From left to right   create,   update,   read,   delete   Corresponding value
const permissionBinary = 0b0010
//   because   update   It is in the third bit to the right, so you only need to move the mask 2 bits to the left
const mask = 0b1 << 2
const result = permissionBinary ^ mask
parseInt(result).toString(2) // 0b0110

After the above content, I believe you have basically mastered the knowledge of bit mask. At the same time, you must have a lot of question marks. For example, is such complex and difficult to read code really meaningful?

Dirty data record

The permission system in the previous example only processes only 4 data, and the bit mask technology is complex and fussy. So are there any scenarios that are really suitable for using bit masks? Dirty data records are one of them.

Suppose we have an original data with the following values:

let A = 'a'
let B = 'b'
let C = 'c'
let D = 'd'

Given a binary number, it corresponds to the status of a / B / C / D from left to right:

let   O  =  0b0000  //  decimal system   0

Once the data is modified, it can be represented by corresponding bits

//   if and only if   A   Has been modified
O  =  0b1000  //  decimal system   eight
//   if and only if   B   Has been modified
O  =  0b0100  //  decimal system   four
//   if and only if   C   Has been modified
O  =  0b0010  //  decimal system   two
//   if and only if   D   Has been modified
O  =  0b0001  //  decimal system   one

Similarly, when multiple data are modified, they can be represented at the same time

//   When   A   and   B   Has been modified
O  =  0b1100  //  decimal system   twelve
//   When   A/B/C   Have been modified
O  =  0b1110  //  decimal system   fourteen

Through this idea, using the idea of permutation and combination, we can quickly know that only 4 bits are needed to express 16 kinds of data changes. Because binary and decimal systems can be converted to each other, only 16 decimal numbers are needed to completely express the changes of the four data of a / B / C / D, that is, dirty data tracking. For example, given a dirty data record 14, binary is converted to   0b1110, so the data indicating a / B / C has been modified.

Svelte is a framework that realizes the response mode through this idea:

if  (  A   The data has changed  ) {
  Update the DOM node corresponding to a
}
if  (  B   The data has changed  ) {
  Update the DOM node corresponding to B
}
/**   Convert to pseudo code  **/
if ( dirty & 8 ) { // 8 === 0b1000
  Update the DOM node corresponding to a
}
if ( dirty & 4 ) { // 4 === 0b0100
  Update the DOM node corresponding to B
}

Rats drink poison

In addition to dirty data recording, bitmask can also be used to deal with the classic problem of “mice drinking poison”.

There are 1000 bottles of water, one of which is poisonous. As long as the mice taste a little poisonous water, they will die 24 hours later. How many mice are required to identify which bottle of water is poisonous within 24 hours?

Let’s simplify the problem by assuming that there are only 8 bottles of water, and its number is expressed in binary:

JS file transfer, 10 HTML file upload skills, web user experience design improvement guide, strange knowledge -- bitmask | si no technology weekly

Then mix the water in the water bottle as shown in the figure to obtain sample a / B / C / d. take four mice numbered a / B / C / D and drink the corresponding water respectively to obtain the following table:

JS file transfer, 10 HTML file upload skills, web user experience design improvement guide, strange knowledge -- bitmask | si no technology weekly

At 24 hours, the death of mice is counted, and the table and results can be obtained after summary:

JS file transfer, 10 HTML file upload skills, web user experience design improvement guide, strange knowledge -- bitmask | si no technology weekly

The answer is imminent. Since eight bottles of water can be mixed with four samples, only four mice are needed to determine which bottle of water is toxic after 24 hours. Back to the topic, if it is 1000 bottles of water, you only need to know the binary number of No. 1000   0b1111101000 is enough. The binary number has a total of 10 bits, which means that 1000 bottles of water can be exchanged for 10 samples, that is, only 10 mice are needed to complete the test task.

Epilogue

That’s all for the exploration of bit mask technology. I believe that after carefully reading this article, we have established the concept of bit mask technology. This is a very special problem-solving idea. Maybe you will really use it one day in the future.


JS file transfer, 10 HTML file upload skills, web user experience design improvement guide, strange knowledge -- bitmask | si no technology weekly