您的当前位置:首页正文

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

2024-11-30 来源:个人技术集锦
<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
    })
}
显示全文