background

Many ToB projects have a form submission requirement in their business, and AntDesgin’s Upload Upload component encapsulates very comprehensive functionality. Now I will introduce how to use the Upload component in combination with the actual project requirements.

Uploading is the process of publishing information (web pages, texts, pictures, and videos) to a remote server through web pages or upload tools.Copy the code

Antdesgin-upload Component documentation ➡️

Feature list

  • Technology stack used in the project: React + Hooks + AntDesgin
  • Actual requirements of the project for uploading function:
    • File upload requires verification [repeatability verification, file quantity limit, file size limit, file format limit, etc.]
    • The file download name must be the same as the file upload name and can be customized
    • The uploaded list can be used to preview files and download files

The actual code

You first need to introduce the relevant dependencies into the page, then write the specific components and page layout in Render.
import React, { useEffect, useState } from 'react';
import { UploadOutlined } from '@ant-design/icons';
import { Button, Upload, message } from 'antd';

const FromComponent = (props) = >{
    return <Upload>
        <Button icon={<UploadOutlined/>}> Upload files</Button>
        <p style={{color:"gray}} ">Supported extension:.doc.docx.pdf.jpg.png</p>
    </Upload>
}
Copy the code

The above code example only shows the default upload effects and functions, and does not implement functions such as limiting files, previewing files, downloading files, and so on. You need to add configuration options and use AntDesgin’s various Api methods to find the ones you need to configure

File processing beforeUpload – beforeUpload(file) hook function
  • Repeatability check
  • File limit
  • File size limit
  • File format Restrictions
// The hook before uploading a file - where fileDateList is the list of uploaded files
beforeUpload: file= > {
  var sameList = fileDateList.filter(item= > item.lastModified == file.lastModified);
  if (sameList.length >= 1) {
    message.error('Do not upload the same file twice');
    return Upload.LIST_IGNORE;
  } else if (fileDateList.length == 10) {
    message.error(The maximum number of files to be uploaded is 10);
  } else if (file.size > 10240000) {
    message.error('The file is too large, please re-select the file within 10M');
    return Upload.LIST_IGNORE;
  } else if(! ['image/png'.'image/jpeg'.'application/pdf'.'application/msword']
    .includes(file.type)) {
      message.error('File format error');
      return Upload.LIST_IGNORE;
  } else if(file.name.length > 50) {
    message.error('Please select a file whose name is less than 50 characters);
    return Upload.LIST_IGNORE;
  } else {
    return true; }},Copy the code
Status of uploaded file changes – onChange(info)
  • Info contains info.file and info.filelist
  • State of the info. The file. The status contains the error | success | done | uploading | removed
  • Info.file. response Indicates the information returned from the file upload backend (as defined by the backend interface of your own project)
  • FileList is an array of file uploads defined by the data format required for submission of your project form
  • Recombine fileDateList because the component checks by default if file has a URL attribute when implementing preview
onChange(info) {
  if (info.file.status === 'done') {            // Add a file
    setFileList([...fileList,{
      fileName: info.file.name,
      fileUrl: info.file.response.data,
    }]);
    if (info.file.response.returnCode == '17000') {
      message.success('File uploaded successfully');
    } else {
      message.error('File upload failed'); }}else if (info.file.status === 'removed') {  // Delete files
    const index = fileList.findIndex(item= >
        item.name === info.file.name);
    fileList.splice(index, 1);
    setFileList(fileList);
  }

  let list = [...info.fileList];                / / restructuring fileDateList
  list = list.map(file= > {
    if (file.response) {
      file.url = file.response.data;
    }
    return file;
  });
  setFileDateList([...list]);
},
Copy the code
Click on the hook function for preview file – onPreview(file)

Adding onPreview overrides the component’s default preview behavior. This overrides the component’s default preview behavior because you need to customize the file name for doc downloads and separate file types.

onPreview(file){                                 // File preview
  if (['image/png'.'image/jpeg'.'application/pdf'].includes(file.type)) {
    var link = document.createElement('a');
    link.target = '_black';
    link.href = file.url;
    link.click();
  } else {
     bizFuns.downLoadFile({
      item: {fileName: file.name,
        fileUrl: file.url,
      }
    })
  }
}
Copy the code

The downLoadFile method is implemented as follows:

// Download the file
downLoadFile(file) {
    var fileName = file.item.fileName;
    var fileUrl = file.item.fileUrl;
    getBlob(fileUrl).then(blob= > {
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
    });
}

// File download gets bloB object
getBlob(url){
    return new Promise(resolve= > {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = 'blob';
        xhr.onload = () = > {
                if (xhr.status === 200) { resolve(xhr.response); }}; xhr.send(); })},Copy the code

Complete configuration sample code attached:

import React, { useEffect, useState } from 'react';
import { UploadOutlined } from '@ant-design/icons';
import { Button, Upload, message } from 'antd';

const FromComponent = (props) = >{
    const [fileList, setFileList] = useState([]);        // List of successfully uploaded files
    const [fileDateList, setFileDateList] = useState([]);// Upload file list (preview)

    // Upload file configuration
    const uploadProps = {
      name: 'file'.maxCount:10.withCredentials: true.// Whether to carry cookies with the upload request
      fileList: fileDateList,                         // List of uploaded files
      action: requestConfig.certificate,              // Upload address
      accept:".doc, .docx, .pdf, .jpg, .png".// Accept the type of file uploaded
      headers: {'X-Access-Token': sessionStorage['X-Access-Token']????' '},
      beforeUpload: file= > {                         // Verify files before uploading
        var sameList = fileDateList.filter(item= > item.lastModified == file.lastModified);
        if (sameList.length >= 1) {
          message.error('Do not upload the same file twice');
          return Upload.LIST_IGNORE;
        } else if (fileDateList.length == 10) {
          message.error(The maximum number of files to be uploaded is 10);
        } else if (file.size > 10240000) {
          message.error('The file is too large, please re-select the file within 10M');
          return Upload.LIST_IGNORE;
        } else if(! ['image/png'.'image/jpeg'.'application/pdf'.'application/msword']
          .includes(file.type)) {
            message.error('File format error');
            return Upload.LIST_IGNORE;
        } else if(file.name.length > 50) {
          message.error('Please select a file whose name is less than 50 characters);
          return Upload.LIST_IGNORE;
        } else {
          return true; }},onChange(info) {
        if (info.file.status === 'done') {            // Add a file
          setFileList([...fileList,{
            fileName: info.file.name,
            fileUrl: info.file.response.data,
          }]);
          if (info.file.response.returnCode == '17000') {
            message.success('File uploaded successfully');
          } else {
            message.error('File upload failed'); }}else if (info.file.status === 'removed') {  // Delete files
          const index = fileList.findIndex(item= >
              item.name === info.file.name);
          fileList.splice(index, 1);
          setFileList(fileList);
        }

        let list = [...info.fileList];
        list = list.map(file= > {
          if (file.response) {
            file.url = file.response.data;
          }
          return file;
        });
        setFileDateList([...list]);
      },
      onPreview(file){                                 // File preview
        if (['image/png'.'image/jpeg'.'application/pdf'].includes(file.type)) {
          var link = document.createElement('a');
          link.target = '_black';
          link.href = file.url;
          link.click();
        } else {
            bizFuns.downLoadFile({
            item: {fileName: file.name,
              fileUrl: file.url,
            }
          })
        }
      }
    };
    
    return <Upload>
        <Button icon={<UploadOutlined/>}> Upload files</Button>
        <p style={{color:"gray}} ">Supported extension:.doc.docx.pdf.jpg.png</p>
    </Upload>
}

export default FromComponent;
Copy the code