vue2 el-upload上传功能

vue2 el-upload上传功能

<template>
  <div class="box-card-div" style="padding-top: 0">
    <el-card class="box-card box-card-div-el-card wow fadeInLeft">
      <template #header>
        <div class="clearfix">
          <span>发布内容公告</span>
        </div>
      </template>
      <div class="components-container">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="标题" prop="title">
            <el-input v-model="ruleForm.title"></el-input>
          </el-form-item>
          <el-form-item label="发布者" prop="publisher">
            <el-input v-model="ruleForm.publisher"></el-input>
          </el-form-item>
          <el-form-item label="图片" prop="image">
            <el-upload
              class="upload-demo"
              ref="upload"
              :file-list="fileList"
              :http-request="uploadFunc"
              :before-upload="beforeUpload"
              :on-remove="removeFile"
            >
              <el-button size="small" type="primary">选取文件</el-button>
              <template #tip>
                <div class="el-upload__tip">只能上传jpg/png文件,仅能上传一张,且不超过2M</div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item label="内容类型" v-if="ruleForm.system === 'activity'">
            <el-select v-model="ruleForm.contentType" placeholder="请选择文章类型">
              <el-option value="1" label="活动">活动</el-option>
              <el-option value="2" label="培训">培训</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否轮播">
            <el-switch
              v-model="ruleForm.isCarousel">
            </el-switch>
          </el-form-item>

          <el-form-item label="标签">
            <el-select v-model="ruleForm.tags" multiple placeholder="请选择标签" style="width: 100%">
              <el-option
                v-for="item in tagsOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="PDF文件">
            <el-upload
              class="upload-demo"
              ref="upload-pdf"
              :on-remove="handlePdfRemove"
              :file-list="pdfFileList"
              :http-request="uploadPdfFunc"
            >
              <el-button size="small" type="primary">选取文件</el-button>
              <template #top>
                <div class="el-upload__tip">只能上传pdf文件</div>
              </template>
            </el-upload>
          </el-form-item>

          <el-form-item label="内容" prop="content">
            <tinymce-editor
              ref="editor"
              v-model:value="ruleForm.content"
              :disabled="disabled"
            />
          </el-form-item>

          <div style="text-align: center; margin-top: 20px">
            <el-button type="primary" @click="submitForm('ruleForm', true)">发布</el-button>
            <el-button type="primary" @click="submitForm('ruleForm', false)">保存草稿</el-button>
          </div>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>

import TinymceEditor from '@/components/editor/TinymceEditor';

import { createContent } from '@/api/cms';
import { uploadFile } from '@/api/files';
export default {
  name: 'Create',
  components: { TinymceEditor },
  data () {
    return {
      domainName: '',
      uploading: false,
      content: '',
      ruleForm: {
        title: '',
        publisher: '',
        content: '',
        contentType: '0',
        system: '',
        type: '',
        image: '',
        pdfFiles: [],
        isFormal: '',
        isCarousel: false,
        tags: []
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        publisher: [
          { required: true, message: '请输入发布者', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]
      },
      fileList: [],
      pdfFileList: [],
      disabled: false,
      tagsOptions: [{
        value: 'mustRead',
        label: '必读'
      }]
    }
  },
  created () {
    this.ruleForm.system = this.$route.query.system
    this.ruleForm.type = this.$route.query.type
    if (this.ruleForm.system === 'activity') {
      this.ruleForm.contentType = '1'
    }
    this.domainName = window.location.origin
  },
  methods: {
    uploadFunc (info) {
      this.uploading = true;
      const { file } = info;
      const formData = new FormData();
      formData.append('file', file);
      uploadFile(formData).then(res => {
        this.fileList.push({
          key: res.fileId,
          url: res.url,
          name: file.name,
        });
        this.ruleForm.image = res.url;
        this.uploading = false;
      }, (err) => {
        this.uploading = false;
        this.$message({
          type: 'error',
          message: `图片 ${file.name} 上传失败:${err.errmsg}`,
        })
        console.error(err);
      });
    },
    beforeUpload () {
      if (this.fileList.length > 0 || this.uploading) {
        this.$message({
          type: 'error',
          message: '图片仅允许上传1张',
        });
      }
    },
    removeFile () {
      this.fileList = [];
    },
    submitForm (formName, isFormal) {
      this.ruleForm.isFormal = isFormal
      this.ruleForm.pdfFiles = this.pdfFileList;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ruleForm.contentType = parseInt(this.ruleForm.contentType)
          createContent(this.ruleForm).then(() => {
            if (isFormal === true) {
              this.$router.push({ path: '/system/article' })
            } else {
              this.$router.push({ path: '/system/draft-box' })
            }
          })
        }
      })
    },
    uploadPdfFunc (info) {
      const { file } = info;
      const formData = new FormData();
      formData.append('file', file);
      uploadFile(formData).then((res) => {
        this.pdfFileList.push({
          key: res.fileId,
          url: res.url,
          name: file.name,
        });
      }, (err) => {
        this.$message({
          type: 'error',
          message: `PDF ${file.name} 上传失败:${err.errmsg}`,
        })
        console.error(err);
      });
    },
    handlePdfRemove (file) {
      const index = this.pdfFileList.findIndex(pdf => pdf.url === file.url);
      this.pdfFileList.splice(index, 1);
    },
  }
}
</script>

<style scoped>
  .box-card-div {
    padding-left: 20px;
    padding-right: 20px;
    padding-bottom: 20px;
  }
</style>

     <div style="display: flex;align-items: center;">
        <el-upload
           class="avatar-uploader upload_file"
           :auto-upload="false"
           :show-file-list="false"
           action=""
           :on-change="handleImport"
         >
           <el-button type="primary">选择文件</el-button>
         </el-upload>
         <span style="font-size: 12px;">支持批量上传,上传格式为excel文件</span>
       </div>


	const handleImport = (file) => {
	  if (file.name.split('.')[1] !== 'xlsx' ||
	   file.raw.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
	      ElMessage({
	        type: 'error',
	        message: '上传文件后缀只能是.xlsx的EXCEL格式文档',
	      });
	      return
	  }
	  const formData = new FormData();
	  formData.append('file', file.raw);
	  // 接口逻辑
	  if (activeTab.value == 2) {
	      importFloor(formData).then(res => {
	        if(res.error_no == 0) {
	          ElMessage.success({
	            message: '上传成功'
	          })
	          showImportDialog.value = false
	          getFloorInfo()
	          // fileList.value.push({id: Math.random(),
	           fileName: file.name.split('.')[0], size: Math.floor(file.raw.size / 1024), status: true})
	        } else if (res.error_no == 4001) {
	          isShowFail.value = true
	          failList.value = res.data.details
	          failUrl.value = res.data.download_fail_url
	          numData.value.total = res.data.total
	          numData.value.success_num = res.data.success_num
	          numData.value.fail_num = res.data.fail_num
	        }
	      })
	  } else if (activeTab.value == 3) {
	    importUnit(formData).then(res => {
	        if(res.error_no == 0) {
	          ElMessage.success({
	            message: '上传成功'
	          })
	          showImportDialog.value = false
	          getUnitInfo()
	          // fileList.value.push({id: Math.random(), fileName: file.name.split('.')[0], size: Math.floor(file.raw.size / 1024), status: true})
	        } else if (res.error_no == 4001) {
	          isShowFail.value = true
	          failList.value = res.data.details
	          failUrl.value = res.data.download_fail_url
	          numData.value.total = res.data.total
	          numData.value.success_num = res.data.success_num
	          numData.value.fail_num = res.data.fail_num
	        }
	      })
	  }
	}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值