el-upload 组件上传/移除/报错/预览文件,预览图片、pdf 等功能

这篇具有很好参考价值的文章主要介绍了el-upload 组件上传/移除/报错/预览文件,预览图片、pdf 等功能。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

页面代码

dialog.vue

<!-- 上传文件 -->
<template>
  <el-dialog
    title="上传文件"
    :visible.sync="dialogVisible"
    width="60%"
    top="6vh"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <ele-form
      ref="submitRef"
      v-model="formData"
      inline
      :form-desc="formDesc"
      :request-fn="handleSubmit"
      :is-show-submit-btn="true"
      :is-show-cancel-btn="true"
      submit-btn-text="确定"
      :is-show-error-notify="false"
      @cancel="handleClose"
    >
      <template v-slot:attachmentList>
        <el-upload
          ref="uploadRef"
          v-loading="uploadLoading"
          class="upload_demo"
          list-type="picture-card"
          :accept="fileTypeList.join(',')"
          action="/supervise_basic/upload/oss/fileupload"
          name="files"
          multiple
          :file-list="fileList"
          :headers="{ 'X-Token': getToken() }"
          :data="{ relativePath: 'SCWS/' }"
          :on-success="onSuccessHandler"
          :on-error="onErrorHandler"
          :on-remove="onRemoveHandler"
          :before-upload="beforeUploadHandler"
        >
          <i slot="default" class="el-icon-plus" />
          <div slot="file" slot-scope="{ file }" class="el_upload_preview_list">
            <!-- pdf 文件展示文件名 -->
            <div v-if="['application/pdf'].includes(file.raw.type)" class="pdfContainer">
              {{ file.name }}
            </div>
            <!-- 图片预览 -->
            <el-image
              v-else
              :id="'image' + file.uid"
              class="el-upload-list__item-thumbnail"
              :src="file.url"
              :preview-src-list="[file.url]"
            />
            <span class="el-upload-list__item-actions">
              <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                <i class="el-icon-zoom-in" />
              </span>
              <span class="el-upload-list__item-delete" @click="onRemoveHandler(file)">
                <i class="el-icon-delete" />
              </span>
            </span>
          </div>
          <template v-slot:tip>
            <div class="el_upload_tip">
              仅支持上传{{ fileTypeList.join('/') }}格式文件,且不超过{{ fileMaxSize }}MB。
            </div>
          </template>
        </el-upload>
      </template>
    </ele-form>
  </el-dialog>
</template>

<script>
import _ from 'lodash.clonedeep'
import { getToken } from '@/utils/tool'
import { uploadBloodFile } from '@/api/blood_api.js'

export default {
  name: 'UploadFileDialog',
  components: {},

  data() {
    return {
      dialogVisible: true,
      rowData: {},
      formData: {
        attachmentList: []
      },
      uploadLoading: false,
      fileTypeList: ['.png', '.jpg', '.jpeg', '.pdf'],
      fileMaxSize: 5,
      fileList: [],
      getToken
    }
  },

  computed: {
    formDesc() {
      return {
        xbrq: {
          type: 'date',
          layout: 24,
          label: '日期',
          required: true,
          attrs: {
            valueFormat: 'yyyy-MM-dd'
          },
          class: {
            textareaTop: true
          },
          style: {
            marginBottom: '10px'
          }
        },
        attachmentList: {
          type: 'upload',
          layout: 24,
          label: '上传文件',
          required: true
        }
      }
    }
  },

  watch: {
    dialogVisible() {
      this.$refs.submitRef &&
        this.$refs.submitRef.$refs.form &&
        this.$refs.submitRef.$refs.form.clearValidate()
    }
  },

  created() {
    const list = []
    this.fileTypeList.forEach((item) => {
      list.push(item, item.toUpperCase())
    })
    this.fileTypeList = [...list]
  },

  methods: {
    open(rowData) {
      console.log('rowData----', rowData)
      this.rowData = _(rowData)

      this.dialogVisible = true
    },

    beforeUploadHandler(file) {
      const ext = file.name.substring(file.name.lastIndexOf('.'))
      const isLt = file.size / 1024 / 1024 < this.fileMaxSize

      if (!this.fileTypeList.includes(ext)) {
        this.$message.error(`请上传${this.fileTypeList.map((item) => item)}格式的文件!`)
        return false // 会调用 on-remove 钩子
      } else if (!isLt) {
        this.$message.error('上传文件大小不能超过 5MB!')
        return false // 会调用 on-remove 钩子
      } else {
        this.uploadLoading = true
        return true
      }
    },

    onRemoveHandler(file, fileList) {
      /**
       * fileList 有无值取决于是上传失败调用 on-remove 钩子,还是手动点击删除按钮删除文件,详细解释如①②:
       *    ① 如果文件上传失败(before-upload 中return false)会自动调用 on-remove 钩子(不用我们自己处理删除文件),此时第二个参数 fileList 有值(为数组);
       *    ② 如果手动点击删除文件按钮删除,此时 fileList 是没有的,为 undefined;
       *    因此通过 fileList 来判断是否执行 on-remove 钩子中我们自己处理移除文件(避免:已经上传了N张图片后,上传不符合要求的图片时调用当前方法导致第 N-1 张图片被删除)
       */
      if (fileList) return

      const { uploadFiles } = this.$refs.uploadRef
      uploadFiles.splice(
        uploadFiles.findIndex((item) => item.uid === file.uid),
        1
      )
      this.formData.attachmentList.splice(
        this.formData.attachmentList.findIndex(
          (item) => item.uid === file.uid && item.filename === file.name
        ),
        1
      )
      this.$refs.submitRef &&
        this.$refs.submitRef.$refs.form &&
        this.$refs.submitRef.$refs.form.validateField('attachmentList')
    },

    // eslint-disable-next-line handle-callback-err
    onErrorHandler(err, file, fileList) {
      this.uploadLoading = false
      this.$message.error(`${file.name}文件上传失败,请重新上传!`)
    },

    // 文件上传成功
    onSuccessHandler(response, file) {
      this.uploadLoading = false
      console.log('response----', response)
      const fileList = response.data.fileUploadInfoList
        ? response.data.fileUploadInfoList.map((item) => {
            return {
              filename: item.filename,
              saved_filename: item.path,
              filetype: item.fileType,
              uid: file.uid
            }
          })
        : []
      this.formData.attachmentList.push(...fileList)
      // 部分表单校验
      this.$refs.submitRef &&
        this.$refs.submitRef.$refs.form &&
        this.$refs.submitRef.$refs.form.validateField('attachmentList')
    },

    // 预览 pdf、图片
    handlePictureCardPreview(file) {
      // 预览pdf
      if (['application/pdf'].includes(file.raw.type)) {
        window.open(file.url)
        return
      }
      // 预览文件
      const imageDom = document.getElementById('image' + file.uid)
      imageDom && imageDom.click()
    },

    handleSubmit() {
      this.$refs.submitRef.validate().then((valid) => {
        const { id, voucher_no } = this.rowData
        const { attachmentList, xbrq } = this.formData
        const params = {
          id,
          voucher_no,
          xgws: attachmentList.map((item) => {
            return {
              wsmc: item.filename,
              wsdz: item.saved_filename,
              xbrq: xbrq
            }
          })
        }
        uploadBloodFile(params).then((res) => {
          this.$common.CheckCode(res, res.msg || '上传成功', () => {
            this.handleClose()
            this.$emit('update')
          })
        })
      })
    },

    handleClose() {
      this.rowData = {}
      this.fileList = []
      for (const key in this.formData) {
        if (this.formData[key] && this.formData[key].constructor === Array) {
          this.formData[key] = []
        } else if (this.formData[key] && this.formData[key].constructor === Object) {
          this.formData[key] = {}
        } else {
          this.formData[key] = ''
        }
      }
      this.dialogVisible = false
    }
  }
}
</script>

<style lang='scss' scoped>
@import '@/styles/dialog-style.scss';
</style>

样式代码

@/styles/dialog-style.scss

::v-deep .el-dialog {
  min-width: 760px;
  .el-dialog__header {
    font-weight: 700;
    border-left: 3px solid #00a4ff;
  }
  .el-dialog__headerbtn {
    top: 13px;
  }

  .ele-form {
    .el-form-item__error {
      top: 75%;
    }
    .el-form-item {
      margin-bottom: 0;
    }
    .ele-form-btns {
      width: 100%;
      .el-form-item__content {
        text-align: right;
      }
    }

    // ele-form 表单项为 textarea 时,当前表单项和上一个表单项校验提示文字位置调整
    .textareaTop {
      & + .el-form-item__error {
        // 上一个表单项检验提示文字位置
        top: 65% !important;
      }
    }
    .currentTextarea {
      & + .el-form-item__error {
        // 当前 textarea 表单项检验提示文字位置
        top: 92% !important;
      }
    }
  }

  .upload_demo {
    margin-top: 8px;
    & + .el-form-item__error {
      top: 156px !important;
    }
  }
}

.dialog_section_title {
  margin: 10px -20px;
  padding: 10px 20px;
  // background-color: #eee;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
  border-left: 3px solid #00a4ff;
  font-weight: 700;
  text-align: left;
}

.noData {
  padding: 10px 0;
  text-align: center;
  color: #ccc;
}

.el_upload_tip {
  margin-top: 15px;
  line-height: 20px;
  text-align: left;
  color: red;
}

.el_upload_preview_list {
  height: 100%;
  // el-uplaod组件卡片预览类型预览pdf样式
  .pdfContainer {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.blue-theme {
  .dialog_section_title {
    border-top: 1px solid #202936;
    border-bottom: 1px solid #202936;
  }
}

.night-theme {
  .dialog_section_title {
    border-top: 1px solid #202936;
    border-bottom: 1px solid #202936;
  }
}

页面展示

el-upload 组件上传/移除/报错/预览文件,预览图片、pdf 等功能,项目问题,elementUI,pdf,javascript,前端
el-upload 组件上传/移除/报错/预览文件,预览图片、pdf 等功能,项目问题,elementUI,pdf,javascript,前端

el-upload 组件上传/移除/报错/预览文件,预览图片、pdf 等功能,项目问题,elementUI,pdf,javascript,前端文章来源地址https://www.toymoban.com/news/detail-736333.html

到了这里,关于el-upload 组件上传/移除/报错/预览文件,预览图片、pdf 等功能的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • element UI el-upload组件实现视频文件上传视频回显

    项目中需要提供一个视频介绍,使用Vue+Element UI中的el-upload组件实现视频上传及进度条展示,后台提供视频上传API并返回URL, 百度找了一番后最终实现了。 HTML JS data css 成功后的截图  

    2024年02月06日
    浏览(35)
  • vue+elementui中el-upload组件上传文件时,修改文件名,不用FormData

    今天在开发的时候,后端突然提了一个需求,因为特殊的文件上传不进文件服务器,所以后端问我能不能上传的时候给加个扩展名,本着只要逻辑没问题,都可以通过代码实现的理念,我说:“可以“”,于是乎有了这篇文章。 首先是去element官网逛了逛,发现也没有提供修

    2024年02月06日
    浏览(36)
  • 【前端学习记录】vue中使用el-upload组件时,上传文件进度条没有实时更新

    问题背景 今天在项目中遇到一个问题,使用el-upload组件时,上传文件进度条没有实时更新,需要手动点击一下才会更新。 原理及可尝试方案 el-upload 组件默认的进度条是通过 Ajax 请求上传文件,并且进度条通过监听 xhr.upload 的 progress 事件来实时更新。但是,有些浏览器在处

    2024年02月01日
    浏览(40)
  • elementUI 的上传组件<el-upload>,自定义上传按钮样式

    原理:调用el-upload组件的方法唤起选择文件事件 效果: 页面代码: js代码:(其他逻辑与element文档的上使用一致) css代码: 隐藏原来的选择图片按钮 原理:把图片显示分离出来,el-upload做选择图片使用,单独做一个显示图片的区域 效果:  页面代码: js 代码: css代码:

    2024年02月13日
    浏览(31)
  • [已解决]前端使用el-upload,后端使用文件上传阿里云报错:异常信息:java.lang.NullPointerException: null

    前端使用el-upload,后端使用文件上传阿里云报错: 报错原因:前端image参数未传进去 解决方法:在el-upload添加属性 name=\\\"image\\\" 文件传进去了!

    2024年01月20日
    浏览(36)
  • vue Element ui上传组件el-upload封装

    注释: 1. limit 可上传图片数量 2. lableName 当前组件name,用于一个页面多次使用上传组件,对数据进行区分 3. upload 上传图片发生变化触发,返回已上传图片的信息 4. imgUrl 默认图片

    2024年02月11日
    浏览(40)
  • elementui el-upload 上传文件

    在使用element中的el-upload上传文件或者图片时,需要先把el-upload的自动上传改为手动上传:auto-upload=“false”然后el-upload内部会调用this.$refs.upload.submit();方法,从而实现多个文件上传。 提示:以下是本篇文章正文内容,下面案例可供参考 代码如下(示例): 需要注意的是 acce

    2024年02月06日
    浏览(37)
  • 【前端相关】elementui使用el-upload组件实现自定义上传

    elmentui 中的upload默认的提交行为是通过 action 属性中输入的 url 链接,提交到指定的服务器上。但是这种url提交文件的方式,在实际的项目环境中往往是不可取的。 我们的服务器会拦截所有的请求,进行权限控制,密钥检查,请求头分析等安全行为控制。写在这里的url无法实

    2024年02月08日
    浏览(42)
  • el-upload上传文件携带额外参数

    在进行文件上传时,需要传递其他参数,比如下图中需要实现携带下拉框的参数 前端实现:将下拉框中的参数 传递到:data中  :data=\\\"{\\\'script_model\\\':script_model}\\\"    后端实现: 从post请求中获取携带的参数:  script_model = request.POST.get(\\\'script_model\\\')

    2024年02月11日
    浏览(39)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包