2023-04-18 11:18:37 +08:00
|
|
|
import type { UploadRawFile } from 'element-plus'
|
|
|
|
|
|
|
|
const message = useMessage() // 消息
|
|
|
|
|
2023-04-21 20:22:11 +08:00
|
|
|
enum UploadType {
|
2023-04-18 11:18:37 +08:00
|
|
|
Image = 'image',
|
|
|
|
Voice = 'voice',
|
|
|
|
Video = 'video'
|
|
|
|
}
|
|
|
|
|
2023-04-21 20:22:11 +08:00
|
|
|
const useBeforeUpload = (type: UploadType, maxSizeMB: number) => {
|
2023-04-18 11:18:37 +08:00
|
|
|
const fn = (rawFile: UploadRawFile): boolean => {
|
|
|
|
let allowTypes: string[] = []
|
|
|
|
let name = ''
|
|
|
|
|
|
|
|
switch (type) {
|
2023-04-21 20:22:11 +08:00
|
|
|
case UploadType.Image:
|
2023-04-18 11:18:37 +08:00
|
|
|
allowTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/jpg']
|
|
|
|
maxSizeMB = 2
|
|
|
|
name = '图片'
|
|
|
|
break
|
2023-04-21 20:22:11 +08:00
|
|
|
case UploadType.Voice:
|
2023-04-18 11:18:37 +08:00
|
|
|
allowTypes = ['audio/mp3', 'audio/mpeg', 'audio/wma', 'audio/wav', 'audio/amr']
|
|
|
|
maxSizeMB = 2
|
|
|
|
name = '语音'
|
|
|
|
break
|
2023-04-21 20:22:11 +08:00
|
|
|
case UploadType.Video:
|
2023-04-18 11:18:37 +08:00
|
|
|
allowTypes = ['video/mp4']
|
|
|
|
maxSizeMB = 10
|
|
|
|
name = '视频'
|
|
|
|
break
|
|
|
|
}
|
|
|
|
// 格式不正确
|
|
|
|
if (!allowTypes.includes(rawFile.type)) {
|
|
|
|
message.error(`上传${name}格式不对!`)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
// 大小不正确
|
|
|
|
if (rawFile.size / 1024 / 1024 > maxSizeMB) {
|
|
|
|
message.error(`上传${name}大小不能超过${maxSizeMB}M!`)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
return fn
|
|
|
|
}
|
|
|
|
|
2023-04-21 20:22:11 +08:00
|
|
|
export { UploadType, useBeforeUpload }
|