elementUI ,封裝文件上傳組件


功能:上傳到指定服務器、刪除文件、點擊文件下載到本地(點擊圖片查看大圖)、限制文件大小。

<template>
  <div>
    <div v-if="!isPicture">
      <el-upload
        action
        class="upload-demo"
        :limit="limit"
        :file-list="formFileList"
        :list-type="isPicture ? 'picture-card' : 'text'"
        :on-change="handleUploadForm"
        :on-exceed="formHandleExceed"
        :before-upload="beforeUploadForm"
        :on-remove="formHandleRemove"
        :on-preview="handlePreview"
        :accept="fileType"
        :auto-upload="false"
      >
        <!--  :show-file-list="false"-->
        <i class="el-icon-plus" v-if="isPicture"></i>
        <template v-else>
          <el-button type="primary" :disabled="disabled">點擊上傳</el-button>
          <i class="tips" >只能上傳文檔,且大小不能超過{{formMaxSize}}M</i>
        </template>
        <!-- <i class="el-icon-plus avatar-uploader-icon"></i> -->
      </el-upload>
    </div>
    <!--圖片上傳組件(帶有縮略圖)。這里分離了出來,如果和非圖片組件寫在一起有問題。-->
    <div v-else>
      <el-upload
        action="#"
        class="upload-demo"
        :limit="limit"
        list-type="picture-card"
        :file-list="formFileList"
        :on-change="handleUploadForm"
        :on-exceed="formHandleExceed"
        :before-upload="beforeUploadForm"
        :accept="fileType"
        :auto-upload="false"
        >
        <i slot="default" class="el-icon-plus"></i>
        <div slot="file" slot-scope="{file}">
          <img
            class="el-upload-list__item-thumbnail"
            :src="file.url" alt=""
          >
          <span class="el-upload-list__item-actions">
        <span
          class="el-upload-list__item-preview"
          @click="handlePreview(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
          v-if="!disabled"
          class="el-upload-list__item-delete"
          @click="handleDownload(file)"
        >
          <i class="el-icon-download"></i>
        </span>
        <span
          v-if="!disabled"
          class="el-upload-list__item-delete"
          @click="formHandleRemove(file)"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
        </div>
      </el-upload>
    </div>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="圖片">
    </el-dialog>
  </div>
</template>
<script>
import url from '@/servers/url-config.js'
import {root} from '@/servers/url-config.js'
import Vue from 'vue'
export default {
  props: {
    id: {  // 業務id
      default: '',
      type: String
    },
    type: {  // 文件code
      default: 'GG',
      type: String
    },
    fileUrl: {  // 文件數組
      default: [],
      type: Array
    },
    fileType: {  // 限制文件類型
      default: 'image/*',
      type: String
    },
    limit: {  // 限制文件個數
      default: 1,
      type: Number
    },
    formMaxSize: {
      default: 10,
      type: Number
    },
  },
  computed: {
    user() {
      return this.$store.state.users.user || JSON.parse(sessionStorage.getItem('user'));
    },
    isYb() {
      return this.$route.path.indexOf('ybrw') > -1
    },
    isPicture () {
      return (this.type == 1 || this.type == 10 || this.type == 3);
    }
  },
  created() {
    // this.$emit('disabled', this.disabled)
  },
  data() {
    return {
      formFileList: [], // 顯示上傳文件
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      data: null,
    };
  },
  watch: {
    fileUrl: {
      deep: true,
      immediate: true,
      handler () {
        this.formFileList = this.fileUrl;
      }
    }
  },
  methods: {

    handlePreview(file) {
      console.log(file,999999)
      if (this.isPicture){
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      } else {
        this.dialogVisible = false; //文件不許預覽
        // 文件允許下載
        if (file.fileid) {
          // 第一次上傳,預覽下載
          window.open(`${root}/system/file/downloadFile?id=${file.fileid}`)
        } else {
          window.open(`${root}/system/file/downloadFile?id=${file.id}`)
        }
      }
    },

    // 開始上傳前驗證
    beforeUploadForm(file) {
      // 驗證文件大小
      if (file.size / 1024 / 1024 > this.formMaxSize) {
        this.$message({
          message: `上傳文件大小不能超過${this.formMaxSize}M!`,
          type: "warning"
        });
        return false;
      }
      // 中文亂碼處理
      // if (file.raw) {
      //   let reader = new FileReader(); // 讀取文件內容
      //   reader.readAsText(file.raw, "gb2312"); // 防止中文亂碼問題,不加reader.onload方法都不會觸發
      //   reader.onload = function(e) {
      //     this.contentHtml = e.target.result; // txt文本內容,接下來就可以對其進行校驗處理了
      //   };
      // }
      // // 驗證文件類型
      // var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      // const extension =
      //   testmsg === "xlsx" || testmsg === "xls" || testmsg === "csv";
      // if (!extension) {
      //   this.$message({
      //     message: "上傳文件只能是xlsx/xls/csv格式!",
      //     type: "warning"
      //   });
      // }
      // return extension;
    },
    // 移除上傳列表中文件
    formHandleRemove(file, formFileList) {
      if(!this.id) {  // 新增
        return;
      };
      let that = this;
      this.$ajax(url.deleteFile, {ids: file.fileid || file.id}).then(res => {
        if (res.success) {
          that.$message({
            type: 'success',
            message: res.message
          });
          // this.$emit('delSuccess', this.data)
          this.data = null;
          that.formFileList.splice(that.formFileList.indexOf(file), 1)
          /*for (let i = 0; i < that.formFileList.length; i++) {
            if (that.formFileList[i].pname === file.name) {
              that.formFileList.splice(i, 1);
              break;
            }
          }*/
          // that.formFileList.splice(formFileList.indexOf(file), 1);
        } else {
          // that.formFileList = [];
          that.$message({
            type: 'info',
            message: res.message
          });
        }
      });
    },
    // 允許上傳文件個數驗證
    formHandleExceed(files, formFileList) {
      this.$message.warning(
        `當前限制選擇 ${this.limit} 個文件,本次選擇了 ${
          files.length
        } 個文件,共選擇了 ${files.length + formFileList.length} 個文件`
      );
    },
    // 圖片點擊下載
    handleDownload(file) {
      this.dialogVisible = false; //文件不許預覽
      // 文件允許下載
      if (file.fileid) {
        // 第一次上傳,預覽下載
        window.open(`${root}/system/file/downloadFile?id=${file.fileid}`)
      } else {
        window.open(`${root}/system/file/downloadFile?id=${file.id}`)
      }
    },
    // 上傳文件
    handleUploadForm(file) {
    //before-upload 是指在文件上傳之前、文件已被選中,但還沒上傳的時候觸發,而設置了 :auto-upload="false" 后,文件上傳事件不被再次調用,,所以 before-upload 不生效,所以,限制圖片大小的時候,需綁定在  :on-change 里面
// 驗證文件大小 if (file.size / 1024 / 1024 > this.formMaxSize) { this.formFileList = []; this.$message({ message: `上傳文件大小不能超過${this.formMaxSize}M!`, type: "warning" }); return false; } let that = this; let formData = new FormData(); formData.append("userId", this.user.id || '123'); // 用戶id formData.append("id", this.id); // 業務id formData.append("type", this.type); // 業務id formData.append("file", file.raw); let loading = that.$loading({ lock: true, text: "上傳中,請稍候...", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)" }); Vue.http.post(url.uploadFile, formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(({data}) => { if (data.success) { that.$message({ type: 'success', message:"上傳文件成功," + data.message }); that.formFileList = that.formFileList.push(data.data); console.log(this.formFileList, 'this.formFileList') // that.$emit('loadSuccess', data.data) // that.formFileList = []; } else { that.formFileList = that.formFileList; that.$message({ type: 'info', message:"上傳文件失敗," + data.message }); } loading.close(); }); } } }; </script>

使用;

<upload
    :id="taskId"
    :type="'9'"
    :limit="10"
    :fileType="'application/msexcel,application/msword,application/pdf,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.wordprocessingml.document, text/plain'"
    :fileUrl="fileUrl9"
    />

import upload from '@/components/upload.vue'

export default {
  components: {
    upload
  },

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM