Detailed explanation of Vue ElementUI manually uploading excel files to the server

Detailed explanation of Vue ElementUI manually uploading excel files to the server

Overview

The specific demand scenarios are as follows:

After selecting the Excel file, you need to manually upload the imported Excel file to the backend server and display the statistical results after successful import. The official website also has examples of manual uploads, which pass in the address through action="url", but in actual projects, requests need to be configured by yourself. The following describes how to do it.

illustrate:

From uploading files to displaying statistical results, our backend provides two interfaces: first, call the file upload interface, and after the upload is successful, call the statistical result interface based on the mark returned by the backend.

Property settings

.vue Files

<el-row>
    <div class="el-form-item__content">
        <el-upload ref="upload"
            accept=".xls,.xlsx"
            action="#"
            :auto-upload="false"
            :multiple="false"
            :file-list="fileList"
            :before-upload="beforeUpload"
            :http-request="uploadHttpRequest"
            :on-remove="fileRemove"
            :on-change="fileChange">
            <el-button size="small" type="primary">Select file</el-button>
            <div slot="tip" class="el-upload__tip">Only one xls/xlsx file can be uploaded at a time, and the file size should not exceed 10M</div>
        </el-upload>
    </div>
</el-row>
<el-row>
    <el-button size="small" @click="closeDialog">Cancel</el-button>
    <el-button type="primary" size="small" @click="submitUpload">Upload</el-button>
    <el-button type="primary" size="small" @click="downloadRes">Download feedback results</el-button>
</el-row>

in:

  • action: The uploaded address. You don’t need to pay too much attention to it, but it is not recommended to delete it. You can use a normal string instead.
  • auto-upload: whether to upload automatically, since this is manual upload, so set it to false
  • multiple: whether to support multiple selections, set to false here
  • file-list: uploaded file list array
  • before-upload: The hook before uploading the file. The parameter is the uploaded file. You can judge the type and size of the uploaded file here.
  • http-request: Customize the upload method, which will override the default upload behavior (i.e. action="url")
  • on-remove: method triggered when the uploaded file is removed
  • on-change: method triggered when the uploaded file status (added, uploaded successfully or failed) changes

Processing Logic

The logic processing code is as follows:

methods: {
    // Hook before uploading files: determine the format and size of the uploaded file, and stop uploading if false is returned beforeUpload(file) {
        //File type const isType = file.type === 'application/vnd.ms-excel'
        const isTypeComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        const fileType = isType || isTypeComputer
        if(!fileType) {
            this.$message.error('Uploaded files can only be in xls/xlsx format!')
        }

        // The file size limit is 10M
        const fileLimit = file.size / 1024 / 1024 < 10;
        if(!fileLimit) {
            this.$message.error('The uploaded file size does not exceed 10M!');
        }
        return fileType && fileLimit
    },
    // Custom upload method, param is the default parameter, you can get the file information, the specific information is as follows uploadHttpRequest(param) {
        const formData = new FormData() //FormData object, adding parameters can only be done through append('key', value) formData.append('file', param.file) //Add file object formData.append('uploadType', this.rulesType)
        const url = `${this.myBaseURL}/operation/ruleImport/importData` //Upload address axios.post(url, formData)
            .then( res => {
                const { data: { code, mark } } = res
                if(code === 0) {
                    param.onSuccess() // Successfully uploaded files display a green check mark this.uploadMark = mark
                }
                return this.countData(this.uploadMark) //Call the statistics result interface according to the response mark value and return a promise for chain call})
            .then( res => { //Chain call, response to statistical results const { data: { code, data } } = res
                if(code === 0) {
                    console.log('Statistical results', data)
                }
            })
            .catch( err => {
                console.log('failed', err)
                param.onError() //Files that failed to upload will be deleted from the file list})
    },
    // Statistical results countFile(mark) {
        return new Promise((resolve, reject) => {
            axios
                .get(`/operation/ruleImport/countData?mark=${mark}`)
                .then(res => {
                    resolve(res)
                })
                .catch(error => {
                    reject(error)
                })
        })
    },
    // Click to upload: Manually upload to the server, which will trigger the component's http-request
    submitUpload() {
        this.$refs.upload.submit()
    },
    // The file changes fileChange(file, fileList) {
        if (fileList.length > 0) {
            this.fileList = [fileList[fileList.length - 1]] // Display the last selected file}
    },
    // Remove the selected files fileRemove(file, fileList) {
        if(fileList.length < 1) {
            this.uploadDisabled = true // Disable the upload button if no file is selected}
    },
    //Cancel closeDialog() {
        this.$refs.upload.clearFiles() //Clear uploaded file object this.fileList = [] //Clear the selected file list this.$emit('close', false)
    }
}

The param parameter of http-request is printed as shown in the figure. Get the current file object through param.file.

The above is a detailed explanation of how to manually upload Excel files to the server using Vue ElementUI. For more information about how to manually upload Excel files to the server using Vue ElementUI, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Implementation of uploading multiple files at once with el-upload in element-ui
  • Element-ui implementation example of multiple file upload
  • vue+element_ui uploads files and passes additional parameters
  • Vue elementUI handles batch file upload

<<:  Solution to the problem that mysql local login cannot use port number to log in

>>:  Summary of learning Docker commands in one article

Recommend

Vue Basics Introduction: Vuex Installation and Use

Table of contents 1. What is vuex 2. Installation...

MySQL 8.0.22 download, installation and configuration method graphic tutorial

Download and install MySQL 8.0.22 for your refere...

8 Reasons Why You Should Use Xfce Desktop Environment for Linux

For several reasons (including curiosity), I star...

Web Design Tips: Simple Rules for Page Layout

Repetition: Repeat certain page design styles thr...

About the configuration problem of MyBatis connecting to MySql8.0 version

When learning mybatis, I encountered an error, th...

Detailed example of HTML element blocking Flash

Copy code The code is as follows: wmode parameter...

Details of various font formats in HTML web pages

This section starts with the details of text modi...

Detailed explanation of the available environment variables in Docker Compose

Several parts of Compose deal with environment va...

How to run a project with docker

1. Enter the directory where your project war is ...

Detailed explanation of JavaScript animation function encapsulation

Table of contents 1. Principle of animation funct...

Detailed explanation of three ways to connect Docker containers to each other

There are three ways to interconnect and communic...

mysql 5.7.23 winx64 decompression version installation tutorial

Detailed installation tutorial of mysql-5.7.23-wi...

Implementation of nginx worker process loop

After the worker process is started, it will firs...