element-ui上传附件和下载附件

上传附件

<el-upload
  ref="upload"
  class="upload-demo"
  :action="uploadUrl()"
  :auto-upload="false"
  :limit="1"
  :headers="headers"
  :on-exceed="handleExceed"
  :file-list="fileList"
  :data="uploadForm"
  :on-success="onSuccess"
  :on-error="onError"
  :on-change="onChange"
  :on-remove="handleRemove"
 >
  <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
</el-upload>

<script>
import {
  mapActions,
  mapGetters
} from 'vuex'
import { getToken } from '@/utils/auth'
import downOrPreview from '../../../utils/downOrPreview.js'
export default {
  data() {
    return {
      addClubDialog: {
        title: '',
        visible: false,
        form: {}
      },
      // 判断是否上传文件
      isUploadFile: false,
      formLabelWidth: '120px',
      fileList: [],
      uploadForm: {},
      rules: {
        clue_company: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        clue_leader: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        clue_contacts: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        clue_state: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        clue_content: [
          { required: true, message: '请输入', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'clueStatus'
    ]),
    headers() {
      return {
        Authorization: 'Token ' + getToken()
      }
    }
  },
  methods: {
    ...mapActions([
      'handleraddClub',
      'handlerUpdateClub',
      'findClueData'
    ]),
    // 新增修改
    uploadUrl() {
      if (this.addClubDialog.form.clue_id) {
        // 修改url
        return downOrPreview.serviceBaseURL(this.addClubDialog.form.clue_id, `crm_clue/update_clue/`)
      } else {
        // 新增url
        return downOrPreview.serviceBaseURL(undefined, `crm_clue/create_clue/`)
      }
    },
    // 打开模态框
    handlerOpen() {
      this.isUploadFile = false
      this.addClubDialog.form = {}
      this.addClubDialog.visible = true
    },
    // 关闭模态框
    handlerClose() {
      this.fileList = []
      this.$refs['addClubDialog.form'].clearValidate()
      this.addClubDialog.visible = false
    },
    // 确定按钮
    saveOrUpdate(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // console.log('=========', this.addClubDialog.form.clue_id)
          // console.log(typeof (this.addClubDialog.form.clue_id) === 'number')
          if (this.addClubDialog.form.clue_id) {
            // 修改
            this.updateClub()
          } else {
            // 新增
            this.addClue()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 保存---新增
    addClue() {
      if (this.isUploadFile) {
        // 新增添加附件
        this.submitUpload()
        this.addClubDialog.visible = false
        // this.isUploadFile = false
        // setTimeout(() => {
        //   this.findClueData()
        // }, 1000)
      } else {
        // 新增却不添加附件
        this.handleraddClub(this.addClubDialog.form).then(() => {
          this.$message({
            message: '新增成功',
            type: 'success'
          })
          this.addClubDialog.visible = false
          this.findClueData()
        }).catch(() => {
          this.$message({
            message: '网络错误',
            type: 'warning'
          })
        })
      }
    },
    // 保存---修改
    updateClub() {
      // this.isUploadFile判断是否上传文件
      // console.log(this.isUploadFile)
      if (this.isUploadFile) {
        this.submitUpload()
        this.addClubDialog.visible = false
        // this.isUploadFile = false
        setTimeout(() => {
          this.findClueData()
        }, 1000)
      } else {
        // 只修改表单
        const params = {
          clue_id: this.addClubDialog.form.clue_id,
          form: this.addClubDialog.form
        }
        delete params.form.clue_id
        this.handlerUpdateClub(params).then(() => {
          this.$message({
            message: '修改成功',
            type: 'success'
          })
          this.addClubDialog.visible = false
          this.findClueData()
        }).catch(() => {
          this.$message({
            message: '网络错误',
            type: 'warning'
          })
        })
      }
    },
    onChange(file, fileList) {
      // console.log(this.addClubDialog.form)
      if ((/.(txt)$/.test(file.name))) {
        this.$message({
          message: '不允许上传以txt结尾的文件',
          type: 'warning'
        })
        this.$refs.upload.clearFiles()
        return
      }
      this.uploadForm = this.addClubDialog.form
      this.isUploadFile = true
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    // 上传
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`)
    },
    onSuccess(files, fileList) {
      this.findClueData()
      this.$message({
        message: '成功',
        type: 'success'
      })
    },
    onError() {
      this.$message({
        message: '网络错误',
        type: 'warning'
      })
    },
    handleRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}?`).then(() => {
        this.isUploadFile = false
      })
    },
    handlePreview(file) {
      console.log(file)
    }
  }
}
</script>

/*
 * @module:
 * @Author: zhangzf
 * @Description: 上传和下载需要用的方法
 */
import service from './request'
const downOrPreview = {}
// 更改baseurl地址,因为有时会有斜杠,有时没有
downOrPreview.uploadURL = function() {
  // console.log(id, url)
  const baseURLArr = service.defaults.baseURL.split('')
  let BASEURL = ''
  if (baseURLArr[baseURLArr.length] !== '/') {
    BASEURL = service.defaults.baseURL + '/'
  } else {
    BASEURL = service.defaults.baseURL
  }
  // console.log(BASEURL)
  return BASEURL
}

downOrPreview.serviceBaseURL = function(id, url) {
  // console.log(id, url)
  const baseURLChange = this.uploadURL()
  // console.log(baseURLChange)
  if (id) {
    return (baseURLChange + url + `${id}/`)
  } else {
    return (baseURLChange + url)
  }
}

export default downOrPreview

下载预览附件

downloadFile(row) {
  // console.log(row)
  this.$confirm('确认下载该附件, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    this.downloadCuleFile(row.clue_id).then((data) => {
    // console.log(data)
    if (data === '无相关附件') {
      this.$message({
        message: '无相关附件',
        type: 'warning'
      })
    } else {
      const word_url = data.match(/media(\S*)/)[0]
      const baseURL = downOrPreview.uploadURL()
      const newHttp = baseURL + word_url
      // 执行下载
      window.location.href = newHttp
    }
  }).catch((error) => {
      console.log(error)
      this.$message({
      type: 'info',
      message: '已取消'
    })
  })
},
posted @ 2020-06-05 15:18  zhongfang99  阅读(4843)  评论(0编辑  收藏  举报