| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- <template>
- <input type="file" ref="fileInput" :accept="accept" style="display: none;" @change="handleUploadFile"/>
- </template>
- <script setup>
- defineOptions({ name: 'upload-file'})
- import { ref } from 'vue'
- import Snackbar from '@/plugins/snackbar'
- import { useI18n } from '@/hooks/web/useI18n'
- import { uploadFile } from '@/api/common'
- const emits = defineEmits(['success'])
- const props = defineProps({
- accept: {
- type: String,
- default: '.pdf,.doc,.docx'
- },
- custom: {
- type: Boolean,
- default: false
- },
- customName: {
- type: String,
- default: ''
- },
- path: {
- type: String,
- default: 'attachment' // attachment附件, img, video
- }
- })
- const { t } = useI18n()
- const clicked = ref(false)
- const fileInput = ref()
- const trigger = () => {
- if (clicked.value) return
- clicked.value = true
- fileInput.value.click()
- clicked.value = false
- }
- const handleUploadFile = async (e) => {
- if (!e.target.files.length) return
-
- const file = e.target.files[0]
- const size = file.size
- if (size / (1024*1024) > 20) {
- Snackbar.warning(t('common.fileSizeExceed'))
- return
- }
- const arr = file.name.split('.')
- // 效验文件格式是否正确
- const fileType = arr[arr.length - 1]
- const acceptArr = props.accept.split(',')
- if (!acceptArr.includes(`.${fileType}`)) return Snackbar.warning('请上传指定格式的文件')
- const formData = new FormData()
- formData.append(props.customName || 'file', file)
- formData.append('path', props.path)
- if (props.custom) return emits('success', formData)
- const { data } = await uploadFile(formData)
- if (!data) return
- emits('success', data, arr[0], file.name)
- }
- defineExpose({
- trigger
- })
- </script>
- <style scoped lang="scss">
- </style>
|