zoukankan      html  css  js  c++  java
  • vue 之 Upload 上传功能

    三种上传功能,写在一个页面上,乱七八糟的记录一下
    <template>
    <div class="app-container">
    <div class="table-wrap">
    <h3 class="table-name">拆分账单</h3>
    <el-form
    ref="analyseForm"
    v-loading="loading"
    :model="analyseForm"
    :rules="rules"
    label-width="150px"
    enctype="multipart/form-data"
    label-position="left"
    style="margin-top: 20px;margin-left: 40px; 80%"
    >
    <el-form-item label="项目" prop="project_id">
    <el-select v-model="analyseForm.project_id" style=" 100%" :placeholder="$t('actions.Select')">
    <el-option
    v-for="item in projectArr"
    :key="item.id"
    :label="item.name"
    :value="item.id"
    />
    </el-select>
    </el-form-item>
    <el-form-item :label="$t('billing.file')" prop="file">
    <el-input v-model="analyseForm.file" type="file" :placeholder="$t('billing.file')" @change="inputFileChange"/>
    <p class="input-text">只能上传csv文件,且大小不能超过10Mb</p>
    <ul class="el-upload-list el-upload-list--text">
    <li class="el-upload-list__item is-success" v-for="(item,index) in fileList" :key="index">
    <a class="el-upload-list__item-name">
    <i class="el-icon-document"></i>{{item.name}}
    </a>
    <label class="el-upload-list__item-status-label">
    <i class="el-icon-upload-success el-icon-circle-check"></i>
    </label>
    <i class="el-icon-close" @click="handleRemove(item)"></i>
    </li>
    </ul>
    <div id="picker">请选择</div>
    <div class="progress"> <!-- 进度条 -->
    <div class="progress-bar progress-bar-striped active" role="progressbar" style=" 0"></div>
    </div>

    <el-upload
    class="upload-demo"
    :action="xxxxxx"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :before-remove="beforeRemove"
    :on-success="refreshData"
    :on-error="OnError"
    :headers="setHeader()"
    :data="setData()"
    :before-upload="beforeUpload"
    multiple
    :limit="3"
    :on-exceed="handleExceed"
    :file-list="fileList"
    :disabled="analyseForm.project_id === ''"
    >
    <el-button size="small" type="primary" @click="clickBefore">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">只能上传csv文件,且每个大小不能超过100Mb</div>
    </el-upload>
    </el-form-item>
    <el-form-item style="display: flex; justify-content: flex-end; margin-right: 40px">
    <el-button @click="$router.push({ name: 'Billing Analysis'})">{{ $t('user.cancel') }}</el-button>
    <el-button type="primary" @click="resetForm('analyseForm')">{{ $t('user.reset') }}</el-button>
    <el-button type="primary" @click="submitForm('analyseForm')">{{ $t('user.submit') }}</el-button>
    </el-form-item>
    </el-form>
    </div>
    <div class="table-wrap" style="margin-top: 20px">
    <h3 class="table-name">拆分列表</h3>
    <el-table
    v-loading="listLading"
    :data="tableDate"
    element-loading-spinner="el-icon-loading"
    style=" 100%"
    >
    <el-table-column type="expand">
    <template slot-scope="props">
    <el-form label-position="left" inline class="demo-table-expand">
    <el-form-item label="记录id">
    <span>{{ props.row.id }}</span>
    </el-form-item>
    <el-form-item label="组织id">
    <span>{{ props.row.org_id }}</span>
    </el-form-item>
    <el-form-item label="拆分文件">
    <span v-for="(x,k) in props.row.filenames" :key="k">
    <span>{{ x }}</span>
    <br>
    </span>
    </el-form-item>
    </el-form>
    </template>
    </el-table-column>
    <el-table-column label="日期">
    <template slot-scope="scope">
    <i class="el-icon-time"/>
    <span style="margin-left: 10px">{{ scope.row.create_time }}</span>
    </template>
    </el-table-column>

    <el-table-column
    label="状态"
    prop="status"
    filter-placement="bottom-end"
    >
    <template slot-scope="scope">
    <el-tag
    :type="getStatus(scope.row.status)"
    disable-transitions
    >{{ scope.row.status }}
    </el-tag>
    </template>
    </el-table-column>
    <el-table-column label="项目" prop="name"/>
    <el-table-column label="操作">
    <template slot-scope="scope">
    <el-button
    size="mini"
    type="danger"
    :disabled="isdisable(scope.row.status)"
    @click="deleteRow(scope.$index, scope.row)"
    >删除
    </el-button>
    </template>
    </el-table-column>
    </el-table>
    </div>
    </div>
    </template>

    <script>

    import WebUploader from 'webuploader'
    import 'webuploader/css/webuploader.css'
    import $ from 'jquery'
    import { getUserProject } from '@/api/permission'
    import { splitBilling, getBillingHistory, deleteBillingHistory } from '@/api/new-billing'

    export default {
    name: 'CreateBillingAnalysis',
    data() {
    return {
    xxxxxx: 'http://Billing-178946295....',
    loading: false,
    projectArr: [],
    analyseForm: {
    project_id: '',
    file: '',
    },
    rules: {
    project_id: {required: true, message: '该字段不能为空', trigger: 'blur'},
    file: {required: true}
    },
    fileList: [],
    tableDate: [],
    listLading: true,
    pagesize: 10,
    currpage: 1,
    }
    },
    created() {
    this.getProjectArr()
    this.getBillingHistory()
    },
    mounted() {
    var token = JSON.parse(sessionStorage.getItem('token'))
    var info = JSON.parse(sessionStorage.getItem('profile'))
    var org_id = ''
    for (let i = 0; i < this.projectArr.length; i++) {
    if (this.projectArr[i].id === this.analyseForm.project_id) {
    org_id = this.projectArr[i].org_id
    break
    }
    }
    // var task_id = info.account_id + WebUploader.Base.guid(); //产生task_id
    var task_id = WebUploader.Base.guid(); //产生task_id
    var uploader = WebUploader.create({
    // 实例化 webuploader并进行配置
    swf: '../static/webuploader-0.1.5/Uploader.swf', // swf文件路径
    server: 'http://Billing-178946295.......', // 文件接收服务端。
    pick: '#picker', // 选择文件的按钮。可选。// 内部根据当前运行是创建,可能是input元素,也可能是flash.
    resize: false, // 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!
    auto: true, //是否开启自动上传
    chunked: true, //是否分片
    chunkSize: 10 * 1024 * 1024, //每个分片的大小,这里为10M
    chunkRetry: 3, //某分片若上传失败,重试次数
    threads: 1, //线程数量,考虑到服务器,这里就选了1
    duplicate: true, //分片是否自动去重
    formData: { //每次上传分片,一起携带的数据
    task_id: task_id,
    project_id: this.project_id
    },
    headers: {
    'account_id': info.account_id,
    'token': token,
    'x-requested-org': org_id,
    }
    });
    uploader.on('startUpload', function () { //开始上传时,调用该方法
    $('.progress-bar').css('width', '0%');
    $('.progress-bar').text('0%');
    });

    uploader.on('uploadProgress', function (file, percentage) { //一个分片上传成功后,调用该方法
    $('.progress-bar').css('width', percentage * 100 - 1 + '%');
    $('.progress-bar').text(Math.floor(percentage * 100 - 1) + '%');
    });

    uploader.on('uploadSuccess', function (file) { //整个文件的所有分片都上传成功,调用该方法
    //上传的信息(文件唯一标识符,文件名)
    var data = {'task_id': task_id, 'filename': file.source['name']};
    $.get('/upload/complete', data); //ajax携带data向该url发请求
    $('.progress-bar').css('width', '100%');
    $('.progress-bar').text('上传完成');
    });

    uploader.on('uploadError', function (file) { //上传过程中发生异常,调用该方法
    $('.progress-bar').css('width', '100%');
    $('.progress-bar').text('上传失败');
    });

    uploader.on('uploadComplete', function (file) { //上传结束,无论文件最终是否上传成功,该方法都会被调用
    $('.progress-bar').removeClass('active progress-bar-striped');
    });
    },
    methods: {
    // 获取项目 id
    getProjectArr() {
    return new Promise((resolve, reject) => {
    getUserProject().then(response => {
    if (response.data.code === 200) {
    this.projectArr = response.data.data
    this.tableDate = this.replaceName(this.xxxx)
    } else if (response.data.code === 400) {
    this.$message.warning(response.data.msg)
    } else if (response.data.code === 500) {
    this.$message.error('服务器报错')
    }
    resolve()
    }).catch(error => {
    reject(error)
    this.$message.error('获取项目信息出错,请刷新重试')
    })
    })
    },

    // 获取账单拆分日志
    getBillingHistory() {
    return new Promise((resolve, reject) => {
    getBillingHistory().then(response => {
    if (response.data.code === 200) {
    this.xxxx = response.data.data
    this.tableDate = this.replaceName(this.xxxx)
    this.listLading = false
    } else if (response.data.code === 400) {
    this.$message.warning(response.data.msg)
    this.listLading = false
    } else if (response.data.code === 500) {
    this.$message.error('服务器报错')
    }
    this.listLading = false
    resolve()
    }).catch(error => {
    reject(error)
    this.$message.error('获取账单拆分日志列表出错,请刷新重试')
    })
    })
    },

    replaceName(data) {
    const temp = []
    let i = 0
    let j = 0
    for (i = 0; i < data.length; i++) {
    for (j = 0; j < this.projectArr.length; j++) {
    if (this.projectArr[j].id === data[i].project_id) {
    const item = data[i]
    item.name = this.projectArr[j].name
    temp.push(item)
    break
    }
    }
    }
    return temp
    },

    changeSelect(val) {
    let obj = {}
    obj = this.credentialsList.find(item => {
    return item.id === val
    })
    this.analyseForm.region = ''
    this.account_type = obj.account_type
    },

    inputFileChange() {
    const resultFile = document.querySelector('input[type=file]').files[0] // 当input中选择文件时触发一个事件并让data当中的files拿到所选择的文件
    // 如果文件存在
    if (resultFile) {
    const index = this.fileList.findIndex((item) => {
    if (resultFile.name === item.name) {
    return true
    } else {
    return false
    }
    })
    if (index === -1) {
    // 不存在
    this.fileList.push(resultFile)
    } else {
    // 存在,并且index是obj在arr中的索引值
    }
    }
    },
    // 删除已选中文件
    deleteFile(item) {
    let index = this.fileList.findIndex((itt) => {
    if (item.name === itt.name) {
    return true;
    } else {
    return false;
    }
    });
    if (index === -1) {
    // 不存在
    } else {
    // 存在,并且index是obj在arr中的索引值
    console.log(this.fileList)
    console.log(index)
    // this.fileList.slice(index-1,1)
    this.fileList.remove(index)
    console.log(this.fileList,'====')
    }
    },

    handleRemove(file, fileList) {
    },

    setData() {
    return {
    'project_id': this.analyseForm.project_id
    }
    },
    setHeader() {
    let org_id = ''
    for (let i = 0; i < this.projectArr.length; i++) {
    if (this.projectArr[i].id === this.analyseForm.project_id) {
    org_id = this.projectArr[i].org_id
    break
    }
    }
    const token = JSON.parse(sessionStorage.getItem('token'))
    const info = JSON.parse(sessionStorage.getItem('info'))
    return {
    'x-requested-org': org_id,
    'token': token,
    'account_id': info.account_id
    }
    },
    handlePreview(file) {
    },
    handleExceed(files, fileList) {
    this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`)
    },
    refreshData() {
    this.getBillingHistory()
    },
    // 上传失败回调
    OnError(err, file, fileList) {
    this.$message.error('文件上传失败')
    },
    clickBefore() {
    if (this.analyseForm.project_id === '') {
    this.$message.error('请选择项目')
    }
    },
    beforeUpload(file) {
    if (this.analyseForm.project_id === '') {
    return false
    } else {
    if (file.type === 'text/csv') {
    // return true
    if (file.size / 1024 / 1024 < 100) {
    return true
    } else {
    this.$message.error('上传文件大小不能超过 100MB!')
    return false
    }
    } else {
    this.$message.error('请上传csv文件!')
    return false
    }
    }
    },
    beforeRemove(file, fileList) {
    if (file.type === 'text/csv' && file.size / 1024 / 1024 < 100) {
    return this.$confirm(`确定移除 ${file.name}?`)
    }
    },
    // 点击提交
    submitForm() {
    this.$refs.analyseForm.validate((valid) => {
    if (valid) {
    this.loading = true
    const fd = new FormData() // 上传文件
    for (let i = 0; i < this.fileList.length; i++) {
    fd.append('file', this.fileList[i])
    }
    fd.append('project_id', this.analyseForm.project_id)

    let org_id = ''
    for (let i = 0; i < this.projectArr.length; i++) {
    if (this.projectArr[i].id === this.analyseForm.project_id) {
    org_id = this.projectArr[i].org_id
    break
    }
    }
    splitBilling(fd, org_id).then(response => {
    if (response.data.code === 200) {
    this.loading = false
    this.$refs.analyseForm.resetFields()
    this.fileList = []
    this.$message({
    message: '拆分成功!',
    type: 'success',
    duration: 1000
    })
    } else {
    this.$message.error('拆分失败,请刷新重试')
    }
    }).catch(() => {
    this.$message.error('拆分失败,请刷新重试')
    this.loading = false
    })
    } else {
    this.$message({
    message: '请完善表单信息',
    type: 'error'
    })
    return false
    }
    })
    },

    // 清空重置表单
    resetForm(userForm) {
    this.$refs[userForm].resetFields()
    },
    // 删除表单历史记录
    deleteRow(index, row) {
    this.$confirm('是否确定删除该记录', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
    }).then(() => {
    deleteBillingHistory(row.id).then(res => {
    if (res.data.code === 200) {
    this.tableDate.splice(index, 1)
    this.$message({
    type: 'success',
    message: '删除成功'
    })
    this.getBillingHistory()
    } else if (res.data.code === 400) {
    this.$message({
    type: 'warning',
    message: res.data.msg
    })
    }
    }).catch(() => {
    this.$confirm('删除时遇到错误,请刷新重试', {
    type: 'error'
    })
    })
    })
    },
    getStatus: (role) => {
    if (role === 'pending') {
    return 'info'
    }
    if (role === 'success') {
    return 'success'
    }
    if (role === 'failed') {
    return 'danger'
    }
    },
    isdisable: (status) => {
    if (status === 'pending') {
    return true
    }
    return false
    },


    }
    }
    </script>

    <style lang="scss">
    .el-transfer-panel {
    260px;
    }

    .input-text {
    font-size: 13px;
    color: #999;
    }

    .el-icon-circle-check:before {
    content: "e720";
    }

    </style>
     
  • 相关阅读:
    Sharepoint 2010 使用asp.net web应用程序,调试sharepoint程序 解决办法
    sharepoint 管理中心 修改场管理员密码
    Sharepoint 给文档添加评论功能
    Sharepoint 修改评分列数据显示图标的颜色 (等级)
    sharepoint 启用评分功能
    sharepoint 获取术语集源的术语并绑定到下拉列表中
    逆元 板子
    CodeForces
    SPOJ
    [HAOI2011]Problem b 题解
  • 原文地址:https://www.cnblogs.com/zhou-xm/p/12664115.html
Copyright © 2011-2022 走看看