123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203 |
- <script setup>
- import { ElMessage } from 'element-plus';
- import { ref, useAttrs, watch } from 'vue';
- // import { REQUEST } from '~/utils/request';
- import { getFullUrl, getPartUrl } from '~/utils/helper';
- import user from '~/store/user';
- const token = user.token
- const action = window.GLOBAL_CONFIG.api + '/upload/main/file'
- const data = { token, client: 'web', api: 'json', issubmit: '1', site: 'tyyx' }
- const emit = defineEmits(['update:part', 'update:full', 'update:size', 'update:time', 'compile', 'update:list'])
- const props = defineProps({
- part: String,
- full: String,
- list: Array,
- // kb
- sizeLimit: Number,
- size: String,
- time: String,
- sizeLimitMsg: String
- })
- const attrs = useAttrs()
- const List_part = ref(props.part)
- const List_full = ref(props.full)
- // const List_size = ref(props.size ? parseFloat(props.size) : 0)
- const List_size = ref(0)
- const List_time = ref(props.time ?? (new Date().toLocaleString()))
- const FILE_LIST = ref([])
- function init() {
- if (List_part.value !== undefined && List_part.value !== '' && List_part.value !== null) {
- FILE_LIST.value = List_part.value.split(';').map((part_url, idx) => ({
- part_url: getPartUrl(part_url),
- url: getFullUrl(part_url),
- // _status: 1,
- // uid: Date.now() - idx,
- name: part_url.split('/').pop()
- }))
- }
- if (List_full.value !== undefined && List_full.value !== '' && List_full.value !== null) {
- FILE_LIST.value = List_full.value.split(';').map((item, idx) => {
- const [part_url, name] = item.split('|')
- return ({
- part_url: getPartUrl(part_url),
- url: getFullUrl(part_url),
- // _status: 1,
- name,
- // uid: Date.now() - idx
- })
- })
- }
- console.log('* init :>> ', FILE_LIST.value);
- }
- init()
- watch(() => [props.part, props.full], (n, o) => {
- List_part.value = (props.part)
- List_full.value = (props.full)
- init()
- })
- /**
- * const STATUS_MAP = {
- * 0: 'READY',
- * 1: 'SUCCESS',
- * 2: 'FAIL'
- * }
- */
- function beforeUpload(file) {
- console.log('file : ', file)
- if (props.sizeLimit) {
- const isLtSize = file.size / 1024 < props.sizeLimit;
- // console.log('isLtSize : ', isLtSize, !isLtSize)
- if (!isLtSize) {
- console.log('1 : ')
- const msg = (props.sizeLimitMsg ? `上传文件大小不能超过 ${props.sizeLimitMsg}!` : `上传文件大小不能超过 ${props.sizeLimit}'KB'!`)
- ElMessage.warning(msg);
- }
- return isLtSize;
- }
- }
- function handleSuccess() {
- console.log('handleSuccess :>> ', FILE_LIST.value.map(e => e.status), FILE_LIST.value);
- if (FILE_LIST.value.every(item => item.status === "success")) {
- let part = [];
- let full = [];
- FILE_LIST.value.forEach(item => {
- if (item.percentage === 100) {
- const { url: part_url, file_name } = item.response.data
- part.push(part_url);
- full.push(`${part_url}|${file_name}`);
- List_size.value += item.size ?? 0
- } else {
- part.push(item.part_url);
- full.push(`${item.part_url}|${item.name}`);
- List_size.value += item.size ?? 0
- }
- })
- emit('update:list', part)
- List_full.value = full.join(';')
- List_part.value = part.join(';')
- List_time.value = (new Date().toLocaleString())
- }
- }
- function onRemove(file, fileList) {
- FILE_LIST.value = fileList
- handleSuccess()
- }
- function onExceed() {
- ElMessage.warning(`最多允许上传${attrs.limit}个文件`)
- }
- const dialogImageUrl = ref('')
- const dialogVisible = ref(false)
- const handlePictureCardPreview = (uploadFile) => {
- if (['png', 'jpg', 'jpeg'].includes(uploadFile.url?.split('.').at(-1))) {
- dialogImageUrl.value = uploadFile.url
- dialogVisible.value = true
- }
- }
- /// <summary>
- /// 格式化文件大小的JS方法
- /// </summary>
- /// <param name="filesize">文件的大小,传入的是一个bytes为单位的参数</param>
- /// <returns>格式化后的值</returns>
- function renderSize(filesize) {
- // const unitArr = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
- // const index = Math.floor(Math.log(filesize) / Math.log(1024));
- // const size = (filesize / Math.pow(1024, index)).toFixed(2);
- // return size + unitArr[index];
- return (filesize / 1024).toString()
- }
- watch(() => List_part.value, () => {
- emit('update:part', List_part.value)
- emit('update:full', List_full.value)
- emit('update:size', renderSize(List_size.value))
- emit('update:time', List_time.value)
- emit('compile', FILE_LIST.value)
- console.log('compile');
- })
- function handleRequest(args) {
- // console.log('handleRequest', args)
- REQUEST.upload({
- url: args.action,
- data: {
- ...args.data,
- [args.filename]: args.file,
- },
- // onUploadProgress: () => {
- // // console.log('progressEvent : ', progressEvent)
- // // const percentage = (progressEvent.loaded / progressEvent.total) * 100
- // // args.onProgress({ percentage }, args.file, args.fileList)
- // },
- }).then((res) => {
- console.log('res', res)
- if (res.code === '1')
- args?.onSuccess(res, args.file, args.fileList)
- else
- args?.onError(res, args.file, args.fileList)
- })
- }
- </script>
- <template>
- <!-- :on-preview="handlePictureCardPreview" -->
- <el-upload :action="action" :data="data" name="filedata" :on-success="handleSuccess" :on-remove="onRemove"
- :on-exceed="onExceed" :before-upload="beforeUpload" v-model:file-list="FILE_LIST"
- :on-preview="handlePictureCardPreview" v-bind="attrs" class="w-full" :http-request="handleRequest" >
- <template #default>
- <slot>
- <el-button type="primary">点击上传</el-button>
- </slot>
- </template>
- <template #tip>
- <slot name="tip"></slot>
- </template>
- <template #file>
- <slot name="file"></slot>
- </template>
- </el-upload>
- <el-dialog v-model="dialogVisible">
- <img w-full :src="dialogImageUrl" alt="Preview Image" />
- </el-dialog>
- </template>
|