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

Detailed explanation of how to view the number of MySQL server threads

This article uses an example to describe how to v...

WeChat Mini Programs are shared globally via uni-app

In actual use, it is often necessary to share the...

React example of how to get the value of the input box

React multiple ways to get the value of the input...

HTML line spacing setting methods and problems

To set the line spacing of <p></p>, us...

In-depth explanation of the global status of WeChat applet

Preface In WeChat applet, you can use globalData ...

HTML uses marquee to achieve text scrolling left and right

Copy code The code is as follows: <BODY> //...

Getting Started with Vue 3.0 Custom Directives

Table of contents 1. Custom instructions 1. Regis...

Vue implements the method of displaying percentage of echart pie chart legend

This article mainly introduces the pie chart data...

A brief discussion on what situations in MySQL will cause index failure

Here are some tips from training institutions and...

How to modify the initial password of MySQL on MAC

Problem description: I bought a Mac and installed...

Complete steps to install MySQL 5.5 on CentOS

Table of contents 1. Preparation before installat...

How to implement remote access control in Centos 7.4

1. SSH remote management SSH is a secure channel ...

Discussion on horizontal and vertical centering of elements in HTML

When we design a page, we often need to center th...

Is it necessary to create a separate index for the MySQL partition field column?

Preface Everyone knows that the partition field m...

Mysql: The user specified as a definer ('xxx@'%') does not exist solution

During the project optimization today, MySQL had ...