SoFunction
Updated on 2025-04-04

Detailed implementation process of uploading large file slices in Vue project to realize seconds transmission and breakpoint continuous transmission

1. Inspection points

In Vue projects, uploading large files such as large images and multi-data Excel is a very common requirement. However, due to the large file size and slow upload speed, problems such as transmission interruption are also difficult to avoid. Therefore, in order to improve the upload efficiency and success rate, we need to use slice upload method to realize the functions of file transmission in seconds, breakpoint transmission, error retry, control concurrency, etc., and draw the progress bar.

In this article, we will examine this technology from the following three perspectives:

Technical solution: How to implement functions such as slice upload, file transmission in seconds, breakpoint transmission, error retry, control concurrency and other functions;

Code example: Based on the Vue framework, how to use the axios library and the element-ui component library to achieve the above functions;

Summary: The advantages and limitations of this technology, recommended application scenarios and future development directions.

2. Technical Solution

1. Implement slice upload

Sliced ​​upload refers to dividing large files into several small pieces for uploading, which not only reduces the pressure on the server, but also improves the upload efficiency. We use the File API for file cutting, split the file into fixed-sized chunks (e.g., each chunk is 1MB in size), and upload each chunk to the server via FormData.

2. File transfer in seconds

File transfer in seconds means that when the same file is uploaded, if the file already exists on the server, it does not need to be uploaded again, but directly returns to the address where the file already exists in the server. To realize file transfer in seconds, you can judge by calculating the MD5 check value of the file.

3. Resuming breakpoint

Breakpoint continuous transmission means that when the file upload is interrupted, you can continue to upload from the last breakpoint when uploading again, without the need to re-upload the entire file. Implementing breakpoint continuous transmission can record the upload progress and the status of each block upload (uploaded, not uploaded, upload failed), and judge the blocks that need to be uploaded based on this information during uploading.

4. Retry the error

Uploading may fail due to network reasons, etc. In order to avoid upload failure, we need to error handling and retry the upload process. We can set a maximum number of retries and retry after the upload fails until the maximum number of retries is reached.

5. Control concurrency

Since uploading requires bandwidth and server resources, uploading multiple files or multiple blocks simultaneously may cause bandwidth and server resources to be tight. Therefore, we need to limit the number of files and blocks uploaded simultaneously to prevent excessive bandwidth and server resources.

3. Code examples

The following is a sample code that uses the axios library and the element-ui component library to implement slice uploading based on the Vue framework:

<template>
  <div>
    <!--Upload components-->
    <el-upload
      class="upload-demo"
      :action="uploadUrl"  // Upload address      :auto-upload="false"  // Disable automatic upload      :on-change="handleChange"  // Triggered when file selection      :before-upload="handleBeforeUpload"  // Triggered before uploading      :on-progress="handleProgress"  // Triggered when upload progress changes    >
      <el-button slot="trigger">Select a file</el-button>  // Select File Button      <!--Upload file button-->
      <el-button style="margin-left: 10px" type="primary" :loading="uploading" :disabled=" === 0" @click="handleUpload">
        Upload file
      </el-button>
      <div class="clearfix"></div>
      <el-progress :percentage="percent"></el-progress>  // Upload progress bar    </el-upload>
  </div>
</template>
<script>
import axios from 'axios';
import { ElMessage } from 'element-ui';  // Introduce the message prompt component in the Element UI libraryexport default {
  data() {
    return {
      files: [],  // Selected file list      uploading: false,  // Is it uploading?      percent: 0,  // Upload progress      uploadUrl: ''  // Upload address    };
  },
  methods: {
    // Upload slices    async upload(file) {
      const chunkSize = 1024 * 1024; // The size of each block is 1MB      const fileSize = ;  // File size      const chunks = (fileSize / chunkSize);  // Total number of blocks      const tasks = [];  // Upload task array      let uploaded = 0;  // Number of uploaded blocks      // File cutting      for (let i = 0; i < chunks; i++) {
        const start = i * chunkSize;
        const end = (start + chunkSize, fileSize);
        (
          new Promise((resolve, reject) => {
            const formData = new FormData();
            ('chunk_index', i);  // Block number            ('chunk_count', chunks);  // Total number of blocks            ('file_id', );  // File ID            ('chunk_data', (start, end));  // Block data            axios
              .post(, formData)  // Upload block data              .then(res => {
                uploaded++;
                 = ((uploaded / chunks) * 100);
                resolve();
              })
              .catch(err => {
                reject(err);
              });
          })
        );
      }
      // After all blocks are uploaded, send a merge request      await (tasks);
      const res = await (, { file_id: , chunks });
      // Upload successfully, return the file URL      if ( === 200) {
        return `${}/${}`;
      } else {
        throw new Error();
      }
    },
    handleChange(files) {
       = files;
    },
    async handleUpload() {
      try {
         = true;
        for (let i = 0; i < ; i++) {
          const file = [i];
          const url = await (file);
          // File upload is successful and the URL is displayed to the user          (`document${}Upload successfully!URL:${url}`);
        }
      } catch (err) {
        (`document上传失败!${}`);
      } finally {
         = false;
      }
    },
    handleBeforeUpload() {
      // TODO: Check file size, type, etc.    },
    handleProgress(event, file) {
      // Show upload progress       = (( / ) * 100);
    }
  }
};
</script>

The above code implements a simple slice upload function, including file transmission in seconds, breakpoint transmission, error retry, control concurrency and other functions, and draws a progress bar.

4. Summary

Slice upload technology is a very practical technology, especially suitable for large file uploads. It not only improves upload efficiency and success rate, but also reduces the pressure on the server. However, slicing upload technology also has its limitations, such as preprocessing of files before uploading, and the server needs to support this technology. Therefore, when using slice upload technology, you need to weigh the pros and cons and choose the solution that suits you.

In the future, with the continuous development of hardware and network technology, slice upload technology will be widely used, and there will be more optimizations and improvements to make it more efficient, stable and easy to use.

This is the article about uploading large file slices in Vue project to achieve instant transfer and breakpoint transfer. For more related contents of Vue large file slices, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!