进行一次上传文件前,校验zip包内图片大小,格式,压缩包大小格式等
ant组件上传前处理/代码块
...
const { limit, zipLimit, zipName, handleLimitZipPic } = props
const beforeUpload: any = async (file: any) => {
console.log('file', file)
const name = file.name
const isZip = !!name.includes('zip')
if (isZip && zipName && name.split(".")[0] !== zipName) {
message.error(`压缩包名称必须为:${zipName}`)
return Promise.reject()
}
if (isZip && zipLimit) {
const isLt20M = file.size / 1000 / 1000 > zipLimit
if (isLt20M) {
message.error(`压缩包文件大小不能超过${zipLimit}M`)
return Promise.reject()
}
}
if (limit) {
const isLt1M = file.size / 1000 / 1000 > limit
if (isLt1M) {
message.error(`文件大小不能超过${limit}M`)
return Promise.reject()
}
}
if (isZip && handleLimitZipPic) { // 处理压缩包里的内容
await validateZip(file)
}
return new Promise((resolve, reject) => {
...
resolve(file)
})
}
...
业务块
...
import JSZip from 'jszip'
...
/** 返回真实file文件的内容,包括压缩包,目前暂不支持excel */
const handleLimitZipPic = (str: any) => {
const isMac = function () {
return /macintosh|mac os x/i.test(navigator.userAgent);
}();
return new Promise((resolve, reject) => {
JSZip.loadAsync(str, {
base64: true
}).then(function (zip) {
zip.forEach(function (relativePath, zipEntry: any) {
console.log('zipEntry', zipEntry)
/** 校验压缩包是否都是jpg和png为后缀的图片 */
// console.log(2333, zipEntry?.name.includes('.png') || zipEntry?.name.includes('.jpg'));
if (isMac) {
if (!(zipEntry?.name.includes('__MACOSX/') || zipEntry?.name.includes('.png') || zipEntry?.name.includes('.jpg'))) {
message.warn('压缩包必须全部都是以PNG/JPG格式的图片')
return reject('压缩包必须全部都是以PNG/JPG格式的图片')
}
} else {
if (!(zipEntry?.name.includes('.png') || zipEntry?.name.includes('.jpg'))) {
message.warn('压缩包必须全部都是以PNG/JPG格式的图片')
return reject('压缩包必须全部都是以PNG/JPG格式的图片')
}
}
if (zipEntry?._data?.uncompressedSize) {
const size = zipEntry?._data?.uncompressedSize
const isLt200k = size / 1000 > imgSingeleSizeLimit
if (isLt200k) {
const tip = `部分图片大小超过${imgSingeleSizeLimit}K,请重试`
message.error(tip)
return reject(tip)
}
}
});
return resolve(true)
}, function (err: any) {
console.log('err', err)
return reject(err)
});
})
}
...