index.vue 12.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
<!--
 * @Date: 2022-08-31 16:16:49
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2024-07-27 19:30:34
 * @FilePath: /data-table/src/components/FileUploaderField/index.vue
 * @Description: 文件上传控件
-->
<template>
  <div v-if="HideShow" class="file-uploader-field">
    <div class="label">
      <span v-if="item.component_props.required">&nbsp;*</span>
      {{ item.component_props.label }}
    </div>
    <div
      v-if="item.component_props.note"
      v-html="item.component_props.note"
      style="font-size: 0.9rem; margin-left: 1rem; color: gray; padding-bottom: 0.5rem; padding-top: 0.25rem; white-space: pre-wrap;"
    />
    <div v-if="!item.component_props.readonly" class="upload-wrapper">
      <div>
        <p
          v-for="(file, index) in fileList"
          :key="index"
          style="padding-left: 1rem; margin-bottom: 0.5rem"
        >
          <p style="font-size: 1rem; word-break: break-all; margin-right: 0.75rem;">
            <span>{{ index + 1 }}.&nbsp;{{ file.name }}&nbsp;&nbsp;{{ (file.size / 1024 / 1024).toFixed(2) }}MB</span>
            &nbsp;&nbsp;
            <span style="color: #e32525; font-size: 0.85rem" @click="beforeDelete(file)">移除</span>
          </p>
        </p>
      </div>
      <div style="padding: 1rem">
        <van-uploader
          :name="item.name"
          upload-icon="add"
          accept="*"
          :before-read="beforeRead"
          :after-read="afterRead"
          :before-delete="beforeDelete"
          :multiple="item.component_props.max_size > 1"
        >
          <van-button icon="plus" type="primary">上传文件</van-button>
        </van-uploader>
      </div>
      <!-- <div class="type-text">上传格式:{{ type_text }}</div> -->
      <div
        v-if="show_empty"
        class="van-field__error-message"
        style="padding: 0 1rem 1rem 1rem"
      >
        文件上传不能为空
      </div>
      <van-divider />
    </div>
    <div v-else style="padding: 1rem;">
        <!-- <a
          v-for="(item, index) in default_file" :key="index"
          :href="item.url"
          :download="item.name"
          style="color: #000; font-size: 0.9rem; text-decoration: underline; margin-right: 0.5rem;"
        >
          {{ item.name }}
        </a> -->
        <a
          @click="downloadFile(item)"
          v-for="(item, index) in default_file" :key="index"
          style="color: #000; font-size: 0.9rem; text-decoration: underline; margin-right: 0.5rem; cursor:pointer;"
        >
          {{ item.name }}
        </a>
    </div>
  </div>

  <van-overlay :show="loading">
    <div class="wrapper" @click.stop>
      <van-loading vertical color="#FFFFFF">上传中...</van-loading>
    </div>
  </van-overlay>
</template>

<script setup>
/**
 * 文件上传
 * @param name[String] 组件名称
 * @param file_type[Array] 文件上传类型
 * @param multiple[Boolean] 文件多选
 */
import { showSuccessToast, showFailToast, showToast } from "vant";
import _ from "lodash";
import { v4 as uuidv4 } from "uuid";
import { qiniuTokenAPI, qiniuUploadAPI, saveFileAPI } from "@/api/common";
import BMF from "browser-md5-file";
import { useRoute } from "vue-router";
import axios from "axios";
import { getEtag } from "@/utils/qetag.js"; // 生成hash值
import { wxInfo } from "@/utils/tools";

const $route = useRoute();
const props = defineProps({
  item: Object,
});
// 隐藏显示
const HideShow = computed(() => {
  return !props.item.component_props.disabled
})
const emit = defineEmits(["active"]);
const show_empty = ref(false);
const default_file = ref(props.item.component_props.default);

onMounted(() => {
  // 非只读模式并且有默认值时
  if (!props.item.component_props.readonly && props.item.component_props.default) {
    fileList.value = default_file.value;
  }
})

const downloadFile = (item) => {
  if (wxInfo().isWeiXin) {
    // 在微信内置浏览器中,直接跳转到手机自带浏览器中下载文件
    window.location.href = item.url;
  } else {
    // 不在微信内置浏览器中,直接打开下载链接
    fileLinkToStreamDownload(item.url, item.name, item.name.split('.').pop());
  }
}

// TAG: 文件下载操作
/**
 * 数据流下载
 * @param {*} url
 * @param {*} fileName
 * @param {*} type
 */
const fileLinkToStreamDownload = (url, fileName, type) => {
  let reg =
    /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\/])+$/;
  if (!reg.test(url)) {
    throw new Error("传入参数不合法,不是标准的文件链接");
  } else {
    let xhr = new XMLHttpRequest();
    xhr.open("get", url, true);
    xhr.setRequestHeader("Content-Type", `application/${type}`);
    xhr.responseType = "blob";
    xhr.onload = function () {
      if (this.status == 200) {
        //接受二进制文件流
        var blob = this.response;
        downloadExportFile(blob, fileName, type);
      }
    };
    xhr.send();
  }
}
/**
 * 下载文件
 * @param {*} blob
 * @param {*} fileName
 * @param {*} fileType
 */
const downloadExportFile = (blob, fileName, fileType) => {
  let downloadElement = document.createElement("a");
  let href = blob;
  if (typeof blob == "string") {
    downloadElement.target = "_blank";
  } else {
    href = window.URL.createObjectURL(blob); //创建下载的链接
  }
  downloadElement.href = href;
  downloadElement.download = fileName;
  document.body.appendChild(downloadElement);
  downloadElement.click(); //点击下载
  document.body.removeChild(downloadElement); //下载完成移除元素
  if (typeof blob != "string") {
    window.URL.revokeObjectURL(href); //释放掉blob对象
  }
}
/************ END ************/

// 文件类型中文页面显示
const type_text = computed(() => {
  return props.item.component_props.file_type;
});
// 上传文件集合
const fileList = ref([
  // { url: "https://fastly.jsdelivr.net/npm/@vant/assets/leaf.jpeg" },
  // Uploader 根据文件后缀来判断是否为文件文件
  // 如果文件 URL 中不包含类型信息,可以添加 isImage 标记来声明
  // { url: 'https://cloud-image', isImage: true },
]);

// 上传前置处理
const beforeRead = (file) => {
  // TODO: 需要file_type集合
  // 类型限制
  // const file_types = _.map(
  //   props.item.component_props.file_type.split("/"),
  //   (item) => `video/${item}`
  // );
  let flag = true;
  if (file.length + 1 > props.item.component_props.max_count) {
    // 数量限制
    flag = false;
    showToast(`最大上传数量为${props.item.component_props.max_count}个`);
  }
  if (fileList.value.length + 1 > props.item.component_props.max_count) {
    // 数量限制
    flag = false;
    showToast(`最大上传数量为${props.item.component_props.max_count}个`);
  }
  if ((file.size / 1024 / 1024).toFixed(2) > props.item.component_props.max_size) {
    // 体积限制
    flag = false;
    showToast(
      `最大文件体积为${props.item.component_props.max_size}MB`
    );
  }
  // if (_.isArray(file)) {
  //   // 多张文件
  //   const types = _.difference(_.uniq(_.map(file, (item) => item.type)), file_types); // 数组返回不能上传的类型
  //   if (types.length) {
  //     flag = false;
  //     showFailToast("请上传指定格式文件");
  //   }
  // } else {
  //   if (!_.includes(file_types, file.type)) {
  //     showFailToast("请上传指定格式文件");
  //     flag = false;
  //   }
  // }
  return flag;
};

// 文件读取完成后的回调函数
const afterRead = async (files) => {
  if (Array.isArray(files)) {
    // 多张文件上传files是一个数组
    muliUpload(files);
  } else {
    const imgUrl = await handleUpload(files);
    // 上传失败提示
    if (!imgUrl.src) {
      files.status = "failed";
      files.message = "上传失败";
      loading.value = false;
    } else {
      files.status = "";
      files.message = "";
      fileList.value.push({
        // meta_id: imgUrl.meta_id,
        name: files.file.name,
        url: imgUrl.src,
        size: files.file.size
        // isImage: true,
      });
      loading.value = false;
    }
  }
  // 过滤非包含URL的文件
  fileList.value = fileList.value.filter((item) => {
    if (item.url) return item;
  });
  props.item.value = {
    key: "file_uploader",
    filed_name: props.item.key,
    // value: fileList.value.map((item) => item.url),
    value: fileList.value,
  };
  show_empty.value = false;
  // 完整数据回调到表单上
  emit("active", props.item.value);
};

// 文件删除前的回调函数
const beforeDelete = (files) => {
  fileList.value = fileList.value.filter((item) => {
    if (item.url !== files.url) return item;
  });
  props.item.value = {
    key: "file_uploader",
    filed_name: props.item.key,
    // value: fileList.value.map((item) => item.url),
    value: fileList.value,
  };
  // 完整数据回调到表单上
  emit("active", props.item.value);
};

/********** 上传七牛云获取文件地址 ***********/
const loading = ref(false);
const formCode = $route.query.code; // 表单code

// 上传文件返回文件URL
const handleUpload = async (files) => {
  loading.value = true;
  // 获取HASH值
  // const hash = getEtag(files.content);
  return new Promise((resolve, reject) => {
    // 获取MD5值
    const bmf = new BMF();
    bmf.md5(
      files.file,
      async (err, md5) => {
        if (err) {
          console.log(err);
          reject(err);
        }
        // 获取七牛token
        const filename = files.file.name; // 真实文件名
        const getToken = await qiniuTokenAPI({
          name: filename,
          hash: md5,
        });
        // 文件上传七牛云
        let imgUrl = "";
        // 第一次上传
        if (getToken.token) {
          files.status = "uploading";
          files.message = "上传中...";
          // 返回数据库真实文件地址
          imgUrl = await uploadQiniu(files.file, getToken.token, filename, md5);
        }
        // 重复上传
        if (getToken.data) {
          imgUrl = getToken.data;
        }
        resolve(imgUrl);
      },
      (process) => {
        //计算进度
      }
    );
  });
};

// 多选文件上传遍历
var muliUpload = async (files) => {
  for (let item of files) {
    const res = await handleUpload(item);
    // 上传失败提示
    if (!res.src) {
      item.status = "failed";
      item.message = "上传失败";
      loading.value = false;
    } else {
      item.status = "";
      item.message = "";
      fileList.value.push({
        // meta_id: res.meta_id,
        name: item.file.name,
        url: res.src,
        size: files.file.size
        // isImage: true,
      });
      loading.value = false;
    }
  }
};

// 生成数据库真实文件地址
const uploadQiniu = async (file, token, name, md5) => {
  let suffix = /\.[^\.]+$/.exec(name); // 获取后缀
  // let affix = uuidv4();
  let fileName = `uploadForm/${formCode}/${md5}${suffix}`;
  let formData = new FormData();
  formData.append("file", file); // 通过append向form对象添加数据
  formData.append("token", token);
  formData.append("key", fileName);
  let config = {
    headers: { "Content-Type": "multipart/form-data" },
  };
  // 自拍文件上传七牛服务器
  let qiniuUploadUrl;
  if (window.location.protocol === 'https:') {
      qiniuUploadUrl = 'https://up.qbox.me';
  } else {
      qiniuUploadUrl = 'http://upload.qiniu.com';
  }
  const { filekey, hash, image_info } = await qiniuUploadAPI(
    qiniuUploadUrl,
    formData,
    config
  );
  if (filekey) {
    // 保存文件
    const { data } = await saveFileAPI({
      name,
      filekey,
      hash: md5,
      // format: image_info.format,
      // height: image_info.height,
      // width: image_info.width,
    });
    return data;
  }
};

/****************** END *******************/

// 校验模块
const validFileUploader = () => {
  if (props.item.component_props.disabled) { // 通过规则隐藏的属性,不校验
    show_empty.value = false;
  } else {
    // 必填项 未上传文件
    if (props.item.component_props.required && !fileList.value.length) {
      show_empty.value = true;
      showToast(props.item.component_props.label + "必填项未填写");
    } else {
      show_empty.value = false;
    }
  }
  return !show_empty.value;
};

defineExpose({ validFileUploader });
</script>

<style lang="less" scoped>
.file-uploader-field {
  .label {
    padding: 1rem 1rem 0 1rem;
    font-size: 0.9rem;
    font-weight: bold;

    span {
      color: red;
    }
  }

  .type-text {
    font-size: 0.9rem;
    margin-left: 1rem;
    padding-bottom: 1rem;
    color: gray;
  }
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.block {
  width: 120px;
  height: 120px;
  background-color: #fff;
}
</style>