vant , 封裝文件上傳組件


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

<template>
  <div>
    <van-uploader
      :after-read="afterRead"
      :before-delete="beforeDelete"
      :max-size="10 * 1024 * 1024"
      @oversize="onOversize"
      @click-preview="click_preview"
      :max-count="1"
      :accept="fileType"
      :disabled="isDone"
      v-model="fileList"
    >
      <template>
        <van-button type="primary">點擊上傳</van-button>
      </template>
    </van-uploader>
  </div>
</template>
<script>
// import url from "@/service/url-config.js";
import api from "@/service/config.js";
import axios from "axios";
export default {
  created() {},
  props: {
    id: String,
    fileUrl: Array,
    type: Number,
    isDone: Boolean,
    fileType: String
  },
  data() {
    return {
      fileList: [],
    };
  },
  watch: {
    fileUrl: {
      deep: true,
      immediate: true,
      handler() {
        this.fileList = this.fileUrl;
      }
    }
  },
  methods: {
    // 文件超過大小
    onOversize(file) {
      console.log(file);
      this.$toast("文件大小不能超過 10M");
    },
    /**文件上傳 */
    afterRead(file) {
      // console.log(file);
      // if (!/image\/[a-zA-z]+/.test(file.file.type)) {
      //   this.$toast("請上傳圖片");
      //   return false;
      // }
      let that = this;
      let params = new FormData();
      params.append("file", file.file);
      params.append("id", this.id);
      params.append("type", this.type);
      let config = {
        headers: {
          //添加請求頭
          "Content-Type": "multipart/form-data"
        }
      };
      axios
        .post(api.api_base + "/system/file/uploadFile", params, config)
        .then(({ data }) => {
          console.log(data, "vvvv");
          that.fileList = [data.data];
        });
    },
    /**文件刪除 */
    beforeDelete(file, detail) {
      let that = this;
      console.log(file, detail);

      this.$http
        .post(api.api_base + "/system/file/deleteFile", {
          ids: file.fileid || file.id
        })
        .then(res => {
          // console.log(res,'刪除成功')
          that.fileList.splice(detail.index, 1);
          this.$toast({
            message: res.message
          });
        });
    },
    /* 文件下載 */
    click_preview(file) {
      if(file.fileid) {
        // 第一次上傳,預覽下載
        window.open(
          `${api.api_base}/system/file/downloadFile?id=${file.fileid}`
        );
      } else {
        window.open(`${api.api_base}/system/file/downloadFile?id=${file.id}`);
      }
    }
  }
};
</script>

 


免責聲明!

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



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