el-upload使用http-request而非默认action地址来实现文件上传

本文介绍el-upload组件的使用方法及自定义上传实现。通过实例展示了如何配置文件类型限制、监听上传进度与错误处理等,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果el-upload没有使用http-request属性,进行接口请求上传文件,那么就会默认使用action的地址作为上传的地址。
如果使用http-request属性那么就会覆盖默认的上传行为,可以自定义上传的实现。(即使action提供了地址也是无效的,被覆盖掉了)。
accept:接受上传的文件类型, accept=".zip",选择文件时只会看到.zip可供选择。
UploadDialog.vue:

<template>
    <el-dialog
        v-el-drag-dialog
        :visible.sync="dialogVisible"
        title="选择文件导入"
        :close-on-click-modal="false"
        width="350px"
        @close="$emit('update:visible',false)"
    >
        <el-upload
            v-loading="loading"
            class="upload-demo"
            action="https://jsonplaceholder.typicode.com/posts/"
            multiple
            :limit="1"
            :file-list="fileList"
            accept=".zip"
            auto-upload
            :on-success="onSuccess"
            :on-error="onError"
            :on-progress="onProgress"
            :http-request="httpRequest"
            :on-change="onChange"
        >
            <el-button size="small" type="primary">选择文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传.zip包,不能不超过500M</div>
        </el-upload>
    </el-dialog>
</template>

<script>
import { pipeDefectImport } from '@/api/drainage-facilities/pipewell/problem-manage'

export default {
    props: {
        visible: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            fileList: [],
            loading: false
        }
    },
    computed: {
        dialogVisible: {
            get() {
                return this.visiblejie
            },
            set(newVal) {
                console.log(newVal)
            }
        }
    },
    methods: {
      //接口上传文件
        async httpRequest(item) {
            this.loading = true
            const fd = new FormData()
            fd.append('file', item.file)
            const res = await pipeDefectImport(fd)
            console.log('zip包上传结果:', res)
        },
      //上传文件成功后
        onSuccess(response, file, fileList) {
            console.log('----onSuccess----', response, file, fileList)
            this.$message.success('导入成功')
            this.loading = false
            this.fileList = [] //清空文件显示列表
            this.$emit('update:visible', false) //关闭文件选择的弹窗
            this.$emit('upload-success')//触发父组件中方法刷新列表数据
        },
        onError(err, file, fileList) {
            console.log('----onError----', err, file, fileList)
            this.loading = false
        },
        onProgress(event, file, fileList) {
            console.log('----onProgress----', event, file, fileList)
        },
        onChange(file, fileList) {
            console.log('----onChange----', file, fileList)
        }

    }
}
</script>

problem-manage.js:

import request from '@/api'
// 管道缺陷导入
export function pipeDefectImport(data) {
    return request({
        url: '/agcloud/pipe/inner/check/result/import',
        method: 'post',
        timeout: 1000000,//超时时间需要设置的较大,否则容易上传失败
        headers: {
            'Content-Type': 'multipart/form-data'//文件上传需要设置该参数
        },
        data
    })
}
在`el-upload`组件中,如果你选择通过`http-request`自定义上传文件,通常会涉及到一个后台API来处理文件上传。要获取上传进度,你需要在发送请求时监听返回的状态码、响应体中的进度信息或者是设置一个上传进度事件。 以下是一个基本的步骤: 1. 在发送HTTP请求前,初始化一个变量存储上传进度,例如`uploadProgress = 0`。 2. 当发送异步上传请求时,添加一个`on-progress`回调函数,这个函数会在每次文件上传过程中接收一个`progress`参数,它是当前的上传百分比。例如在axios或fetch中可以这样做: ```javascript const sendUploadRequest = async (file) => { const uploadProgress = 0; // 初始化上传进度 try { const response = await axios.post('/api/upload', { file }, { onUploadProgress: (progressEvent) => { uploadProgress = Math.round(progressEvent.loaded * 100 / progressEvent.total); } }); // 在这里处理服务器的响应 console.log(response); // 更新上传进度到前端 UI this.uploadProgress = uploadProgress; } catch (error) { console.error('Error uploading:', error); } }; ``` 3. 在`el-upload`的配置中,你可以使用`on-change`事件来触发上传,并传入`sendUploadRequest`函数: ```html <template> <el-upload :action="uploadUrl" :on-change="sendUploadRequest" ...其他属性... ></el-upload> </template> <script> export default { data() { return { uploadProgress: 0, uploadUrl: 'your-api-url', }; }, methods: { sendUploadRequest(file) { this.sendUploadRequest(file); } } }; </script> ``` 这样,在用户上传文件的过程中,你就可以在`this.uploadProgress`上看到实时的上传进度了。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值