Summary of picture/file upload scheme based on business scenarios

Wonderful review

Preface

The image/file upload group is one of the indispensable links in the development of enterprise projects, but all user modules will have image/file upload requirements. It is also a basic component in many third-party component libraries (ant desigin, element ui) One. Next, I will take you to implement a picture/file upload component from scratch and expand a more powerful upload component.

You will gain

  • Commonly used picture upload function realization scheme

  • Handwriting a picture/file upload component

  • How to integrate the cropping function into the upload component

  • Image autonomy scheme under content platform/visualization platform

  • How to expand a more powerful image upload solution

text

As a front-end engineer, solving project problems is one of our basic responsibilities. We can use the knowledge we have acquired to solve problems and needs in project development. This is also the first stage of our professional career, namely— —Adaptation period. If we want to continue to be promoted, we need to continue to upgrade and master various skills, so that we can use the best solution to solve problems efficiently in the future when we encounter problems, which is the second stage — -Development period.

In order to enter the development period faster, we need to continuously improve the depth and breadth of our own technology, be able to consider the nature of the problem vertically and propose multiple solutions to the problem horizontally, and finally choose an optimal solution to achieve it. To achieve this, we need to think deeply and review the problem. Next, the author will introduce several commonly used image upload solutions to expand everyone's breadth.

1. Commonly used image upload solutions

Since the web1.0 era, the most commonly used upload solution is the form form. We only need to write various inputs (input elements) in the form and define the upload server address (action). The form is similar. as follows:

<form action="/xuxiaoxi/form/post">
    <div class="form-item"><input type="text" /></div>
    <div class="form-item"><input type="passward" /></div>
    <div class="form-item"><input type="file" /></div>
    <div class="form-item"><input type="submit" /></div>
</form>

复制代码

When XHR technology is not popular, we mostly choose the above solution. The only drawback is that the page will be refreshed after submission. The user experience is not good, and it may cause partial data loss. However, there is still a solution, which is form + iframe technology.

1.1 form + iframe solution

The basic idea of ​​the form + iframe scheme is that our submission action is triggered on the parent page, but the form form is pointed to the iframe, which can achieve partial refresh. Now some scenarios still use this scheme. The specific principles are as follows:

The above two schemes can realize the partial refresh function under the traditional form submission, but scheme one needs to maintain the iframe form separately, so I generally use scheme two, and the compatibility can reach IE9 (although it is compatible with IE browsers for now) Not big, but still need to understand)

1.2 ajax + formData solution

After the popularity of XHR, we can easily use ajax to implement asynchronous requests.For file uploads, we can also use ajax and formData more flexibly to achieve this, and gradually break away from the dependence on native form forms.

The FormData object is used to compile data into key-value pairs for sending data with XMLHttpRequest. It is mainly used to send form data, but can also be used to send keyed data, and is used independently of the form. If the enctype attribute of the form is set to multipart/form-data, the form's submit() method will be used to send the data, so that the sent data has the same form.

Let's first look at a simple example of uploading files using formData:

let formData = new FormData();

// HTML 文件类型input,由用户选择
formData.append("userfile", fileInputElement.files[0]);

let request = new XMLHttpRequest();
request.open("POST", "http://http://io.nainor.com/h5/form");
request.send(formData);

复制代码

The above just 5 lines of code realizes uploading the file to the server through formData, is it very simple? The author's previous article  developed a Moments application dedicated to programmers based on react/vue and adopted this solution. Those who are interested can study and study.

It is also very simple to implement multiple file uploads. Here we take axios as an example. The specific implementation is as follows:

const formData = new FormData()
for(let i=0; i< files.length; i++) {
  formData.append(`file_${i+1}`, files[i].file)
}
axios({
  method: 'post',
  url: '/files/upload/tx',
  data: formData,
  headers: {
      'Content-Type': 'multipart/form-data'
  }
});

复制代码

 Note that for multi-file uploads, you should set the Content-Type to multipart/form-data in the http header of the request. Of course, you can also implement file upload components that are more in line with your own business needs based on the above principles, such as preview, current limit, etc.

1.3 Implementation of third-party components

In order to develop business more efficiently and quickly, we can sometimes choose a third-party more mature solution, such as the upload component of antd, such as the upload component of element ui. Here the author summarizes a few more useful and powerful solutions, you can Feel it:

  • The upload component of antd/element

  • FilePond can upload any content, and can optimize images to speed up the upload speed while providing a smooth user experience

  • Web Uploader Baidu WebFE (FEX) team developed a simple modern file upload component based on HTML5 and supplemented by FLASH

  • vue-simple-uploader Powerful and beautiful file upload component based on vue

We can easily implement powerful upload components through the third-party component libraries provided above, combined with our server configuration.

2. Integrate the cropping function into the image upload component

For image upload components, we are often not sure what the user uploads, so we have to restrict in advance, such as restricting the image size, image format, image ratio, etc. to meet our business standards. Image size and image format The limitation of is very easy to achieve, but for the image ratio, we cannot expect users to handle this by themselves, because this will greatly increase the burden on users to use the website, so we can provide a function for users to cut images online. As shown in the following figure Show:

The above screenshots are from the image upload component of the H5-Dooring online editor. After the user uploads, we will display the image cropping interface. We will specify the ratio of the image to allow the user to freely crop it. The author will use the antd-based upload component with antd- Img-crop will take you to realize the online cutting function. The specific code is as follows:

import React, { useState } from 'react';
import { Upload } from 'antd';
import ImgCrop from 'antd-img-crop';

const Demo = () => {
  const [fileList, setFileList] = useState([
    {
      uid: '-1',
      name: 'image.png',
      status: 'done',
      url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    },
  ]);

  const onChange = ({ fileList: newFileList }) => {
    setFileList(newFileList);
  };

  const onPreview = async file => {
    let src = file.url;
    if (!src) {
      src = await new Promise(resolve => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj);
        reader.onload = () => resolve(reader.result);
      });
    }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow.document.write(image.outerHTML);
  };

  return (
    <ImgCrop rotate>
      <Upload
        action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
        listType="picture-card"
        fileList={fileList}
        onChange={onChange}
        onPreview={onPreview}
      >
        {fileList.length < 5 && '+ Upload'}
      </Upload>
    </ImgCrop>
  );
};

ReactDOM.render(<Demo />, mountNode);

复制代码

The above is just an example of basic cropping and uploading pictures. Of course, antd-img-crop also provides more flexible configurations to facilitate us to design more flexible and powerful cropping effects. Of course, we can also use react-cropper to achieve, It provides more flexible cutting control and real-time preview function, as shown in the figure below:

3. Image autonomy under content platform/visualization platform

For content platforms or visualization platforms, simply uploading pictures cannot meet the needs of users, because content/visualization platforms pay more attention to the selection and use of pictures, and the requirements for pictures are also very high. After all, the resources of users upload by themselves are limited, and they often cannot reach users. The demand for content publishing or the demand for visual design, so the function of image material library is often provided in such platforms. Users can search for massive pictures in the material library to meet their own needs, and often this way, they can stay more Live users and increase user stickiness.

Based on the above scenarios, product managers often put forward such requirements: Can you provide alternatives, users can upload pictures themselves, or use the image library resources we provide? At this time, experienced front-ends often say: Arrange!

Before designing this function, we often have to refer to other existing implementations. Here we give a few examples, as shown in the following figure:

In the above case, we can find that when users upload pictures, two optional options are provided, one is to upload locally, the other is to select directly in the image library, so our solution is similar, and the image library can be packaged in a file upload As a common function in the component, it can also be combined package, each can be used independently or in combination.

For H5-Dooring's encapsulation of the image library, it is implemented as a general service, that is, whenever the upload component is used, an optional button to select from the image library will appear. The implementation scheme is also very simple, that is, in the upload component Expand one layer in the middle, use Modal+Tab to make the picture selection interface, when the selection is completed, manually set the address of the picture to the upload component. The code is as follows:

handleImgSelected= () => {
  const fileList = [
    {
      uid: uuid(8, 16),
      name: 'h5-dooring图片库',
      status: 'done',
      url: this.state.curSelectedImg,
    },
  ];
  this.props.onChange && this.props.onChange(fileList);
  this.setState({ fileList, wallModalVisible: false });
};

复制代码

The controlled mode of antd's form component is used here.

4. Image upload component extension

The solution described above is completely sufficient for basic usage scenarios, but if it is a content website or a visualization platform, because our configuration may be distributed to the public network at any time, this will involve content security issues. If once the user configures Illegal image information may be implicated in the provision of the platform, so we also need to provide a complete review mechanism. For example, after the user configures or publishes the content, it needs to be reviewed before it can be officially published online, but completely Relying on manual review efficiency is relatively low, so at this time we need to find machine automated review solutions. For example, Alibaba Cloud and Tencent Cloud provide services such as image identification. We can integrate these services into our components to achieve Real business autonomy capabilities, so as to more safely carry out enterprise operation and development.

Another requirement is that users have editing needs for uploaded pictures. We can also provide online editing functions for pictures, similar to the following solutions:

We can give users the ability to design their own pictures, add watermarks, etc., is this more interesting?

5. Summary

The author of the above tutorial has been integrated into H5-Dooring. For some more complex interactive functions, it can also be realized through reasonable design. You can explore and study by yourself.

github????:h5-Dooring

At last

If you want to learn more H5 games, webpack, node, gulp, css3, javascript, nodeJS, canvas data visualization and other front-end knowledge and actual combat, welcome to study and discuss together in "Interesting Frontend" to explore the front-end boundary together.

Comment area

Guess you like

Origin blog.csdn.net/KlausLily/article/details/108957829