需求
使用antd的Upload上传.zip压缩包文件
代码
javascript">const [uploadLoaing, setUploadLoaing] = useState(false);// 辅助函数:检查文件是否为zip格式function isZipFile(file: File): boolean {const fileType = file.type;return fileType === 'application/zip' || file.name.endsWith('.zip');}const props= {name: 'file',multiple: false,action: `${envConfig.baseURL}/model/import`, //上传的接口地址headers: {'X-Webtoken': getToken() || '', //请求头携带token},accept: '.zip',showUploadList: false,onChange(info) {console.log('info=>', info);const { status } = info.file;if (status === 'uploading') {setUploadLoaing(true);}if (status === 'done') {if (info.file.response.code === 0) {message.success(`文件导入成功`);setUploadLoaing(false);} else {const errorMsg = info.file.response.data?.[0] || info.file.response.desc || '文件导入失败';message.error(errorMsg);setUploadLoaing(false);}} else if (status === 'error') {message.error(`文件导入失败`);setUploadLoaing(false);}},beforeUpload(file) {const isZip = isZipFile(file);const maxSize = 200 * 1024 * 1024;if (!isZip) {message.error('请上传一个压缩包文件。');} else if (file.size > maxSize) {message.error('文件大小不能超过200兆。');}return isZip && file.size <= maxSize; //若返回false,则阻止上传行为},
};<Upload {...props}><Button loading={uploadLoaing}>上传</Button>
</Upload>