SoFunction
Updated on 2025-04-05

Use ElementUI el-upload to achieve uploading multiple files at once

introduction

In daily front-end development, file upload is a very common requirement, especially in scenarios where users need to upload multiple files at once. As a very excellent 2.0 component library, ElementUI provides us with rich UI components, greatly improving development efficiency. Among them, the el-upload component is a powerful and easy-to-use file upload component.

Introduction to el-upload component

el-upload is a file upload component provided by ElementUI, which supports multiple file upload methods, such as ordinary upload, drag-and-drop upload, image upload, etc. This component not only meets the needs of single file upload, but also easily uploads multiple files at once. More importantly, the API design of the el-upload component is very concise and clear, and developers can flexibly configure it according to their needs.

Basic usage

Before we start explaining the specific implementation, let’s take a look at the basic usage of the el-upload component. Here is a simple single file upload example:

<template>
  <el-upload
    class="upload-demo"
    action="/posts/"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :file-list="fileList"
    :auto-upload="false">
    <el-button slot="trigger" size="small" type="primary">Select a file</el-button>
    <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">Upload to server</el-button>
    <div slot="tip" class="el-upload__tip">Uploadable onlyjpg/pngdocument,And not more than500kb</div>
  </el-upload>
</template>

<script>
  export default {
    data() {
      return {
        fileList: []
      };
    },
    methods: {
      handlePreview(file) {
        (file);
      },
      handleRemove(file, fileList) {
        (file, fileList);
      },
      submitUpload() {
        this.$();
      }
    }
  }
</script>

In this example, we implement a simple file upload function through the el-upload component.actionThe attribute specifies the server address for file upload.file-listUsed to manage selected files lists,on-previewandon-removeThis is used for file preview and delete callbacks respectively.

Implement multi-file upload

In order to upload multiple files at once, we only need to set it in the el-upload componentmultipleJust attributes. This property allows the user to select multiple files at once in the file selection dialog box. Here is an example of multi-file upload:

<template>
  <el-upload
    class="upload-demo"
    action="/posts/"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :file-list="fileList"
    :auto-upload="false"
    multiple>
    <el-button slot="trigger" size="small" type="primary">Select a file</el-button>
    <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">Upload to server</el-button>
    <div slot="tip" class="el-upload__tip">Multiple files can be uploaded</div>
  </el-upload>
</template>

<script>
  export default {
    data() {
      return {
        fileList: []
      };
    },
    methods: {
      handlePreview(file) {
        (file);
      },
      handleRemove(file, fileList) {
        (file, fileList);
      },
      submitUpload() {
        this.$();
      }
    }
  }
</script>

In this example, we addedmultipleProperties, such that the file selection dialog allows multiple files to be selected at once. In this way, users can easily achieve batch uploads.

More configurations for file uploads

The el-upload component not only supports multiple file uploads, but also provides rich configuration items to meet various file upload needs. Below we will introduce some commonly used configuration items in detail:

headers custom request headers

When uploading files, if you need to add a custom request header, you can useheadersProperties are configured. Here is an example of adding a custom request header:

<el-upload
  action="/posts/"
  :headers="{
    Authorization: 'Bearer YOUR_TOKEN'
  }">
</el-upload>

Data upload with parameters

When uploading files, if you need to attach some extra parameters, you can usedataProperties are configured. Here is an example of uploading with extra parameters:

<el-upload
  action="/posts/"
  :data="{
    userId: 123
  }">
</el-upload>

limit limit the number of uploaded files

If you need to limit the number of uploaded files, you canlimitConfigure properties and combine them withon-exceedEvents are processed. Here is an example that limits up to 3 files to be uploaded:

&lt;template&gt;
  &lt;el-upload
    class="upload-demo"
    action="/posts/"
    :file-list="fileList"
    :limit="3"
    :on-exceed="handleExceed"
    multiple&gt;
    &lt;el-button slot="trigger" size="small" type="primary"&gt;Select a file&lt;/el-button&gt;
  &lt;/el-upload&gt;
&lt;/template&gt;

&lt;script&gt;
  export default {
    data() {
      return {
        fileList: []
      };
    },
    methods: {
      handleExceed(files, fileList) {
        this.$(`Current limit selection 3 A file,This time I chose ${} A file,A total of selected ${ + } A file`);
      }
    }
  }
&lt;/script&gt;

before-upload The hook before upload

Before uploading the file, if you need to perform some processing or verification on the file, you can usebefore-uploadhook. Here is an example of file size verification before uploading:

&lt;template&gt;
  &lt;el-upload
    class="upload-demo"
    action="/posts/"
    :before-upload="beforeUpload"
    multiple&gt;
    &lt;el-button slot="trigger" size="small" type="primary"&gt;Select a file&lt;/el-button&gt;
  &lt;/el-upload&gt;
&lt;/template&gt;

&lt;script&gt;
  export default {
    methods: {
      beforeUpload(file) {
        const isLt2M =  / 1024 / 1024 &lt; 2;
        if (!isLt2M) {
          this.$('The upload file size cannot exceed 2MB!');
        }
        return isLt2M;
      }
    }
  }
&lt;/script&gt;

In this example, we check the file size before uploading the file. If the file size exceeds 2MB, an error message will be prompted and upload will be blocked.

Drag and drop upload

The el-upload component also supports drag and drop upload function, and users can upload files by dragging files to a specified area. Here is an example of drag-and-drop upload:

&lt;template&gt;
  &lt;el-upload
    class="upload-demo"
    drag
    action="/posts/"
    multiple&gt;
    &lt;i class="el-icon-upload"&gt;&lt;/i&gt;
    &lt;div class="el-upload__text"&gt;Drag the file here,or&lt;em&gt;Click to upload&lt;/em&gt;&lt;/div&gt;
    &lt;div class="el-upload__tip" slot="tip"&gt;Support batch upload&lt;/div&gt;
  &lt;/el-upload&gt;
&lt;/template&gt;

In this example, we adddragProperties, such that the el-upload component supports drag and drop upload. Users can drag and drop files to a specified area to easily upload files.

Custom upload request

Sometimes we may need to have more fine-grained control over upload requests, such as usingaxiosWait for the library to upload. The el-upload component provideshttp-requestHook, allowing us to customize upload requests. The following is a useaxiosExample of custom upload request:

&lt;template&gt;
  &lt;el-upload
    class="upload-demo"
    :http-request="customRequest"
    multiple&gt;
    &lt;el-button slot="trigger" size="small" type="primary"&gt;Select a file&lt;/el-button&gt;
  &lt;/el-upload&gt;
&lt;/template&gt;

&lt;script&gt;
  import axios from 'axios';

  export default {
    methods: {
      customRequest({ file, onProgress, onSuccess, onError }) {
        const formData = new FormData();
        ('file', file);

        ('/posts/', formData, {
          onUploadProgress: (event) =&gt; {
            let percent = (( * 100) / );
            onProgress({ percent });
          }
        }).then(response =&gt; {
          onSuccess();
        }).catch(error =&gt; {
          onError(error);
        });
      }
    }
  }
&lt;/script&gt;

In this example, we useaxiosThe library has customized the upload request. passhttp-requestWith hook, we can fully control the upload process and implement more flexible upload logic.

summary

ElementUI's el-upload component provides us with powerful file upload functions, which not only supports single file upload, but also allows us to easily upload multiple files at once. By flexibly configuring the various properties and hook functions of the component, we can meet various complex file upload needs. Whether it is adding custom request headers, uploading attached parameters, limiting the number of uploaded files, or dragging and uploading, the el-upload component can easily deal with it.

In daily development, we can customize and optimize the el-upload components in a deeper manner according to actual needs, thereby improving user experience and system performance. I hope this article can help you better understand and use the el-upload component, making file upload easier and more efficient.

The above is the detailed content of using ElementUI el-upload to upload multiple files at once. For more information about uploading multiple files by ElementUI el-upload, please pay attention to my other related articles!