antd 上传进度_antd vue upload组件使用customRequest上传文件显示文件上传进度

antd-vue上传文件upload组件使用自定义上传方法customRequest无法显示文件上传进度条,如下图红框内的进度条无法显示当前文件上传进度

于是,在网上搜索解决方案:

第一种解决方案是自己封装组件,通过axios请求的onUploadProgress来获取文件上传进度,个人觉得太麻烦;

我采用了第二种解决方案,但是使用调用不了参考文章中的`options.onSuccess(res, options.file)`

于是查看了github上的源码,决定通过$refs调用upload组件中显示进度条的方法和上传成功方法:

html部分:

```html

ref="uploadRef"

name="file"

:multiple="false"

:showUploadList="true"

:file-list="fileList"

:customRequest="customRequest"

:remove="removeFile"

@change="fileChange"

>

上传文件

```

js部分:

```javascript

uploadFile('upload_files', fileData.file, {

onUploadProgress: (progressEvent) => {

const percentNum = Math.round((progressEvent.loaded * 100) / progressEvent.total);

this.$refs.uploadRef.onProgress(

{

percent: percentNum

},

fileData.file

)

}

}).then(res => {

fileData.file.status = 'done'

fileData.file.url = this.picsPrefix + res.result

this.$refs.uploadRef.onSuccess(res, fileData.file, '')

})

},

fileChange({ file }) {

if (!file.stop) {

this.fileList = []

this.fileList.push(file)

}

},

```

Ant Design中的Upload组件可以通过设置`showUploadList`属性为`false`,然后使用自定义的进度组件来实现上传进度显示。 以下是一个上传大文件并显示进度进度的示例代码: ```jsx import { Upload, Button } from 'antd'; import { UploadOutlined } from '@ant-design/icons'; import React, { useState } from 'react'; const UploadProgress = ({ percent }) => ( <div style={{ margin: '10px 0' }}> <div style={{ width: `${percent}%`, height: '5px', backgroundColor: '#1890ff' }}></div> </div> ); const Demo = () => { const [uploading, setUploading] = useState(false); const [progress, setProgress] = useState(0); const handleUpload = ({ file }) => { const formData = new FormData(); formData.append('file', file); setUploading(true); // 模拟上传进度 const timer = setInterval(() => { setProgress((prevProgress) => { if (prevProgress >= 100) { clearInterval(timer); setUploading(false); return 100; } else { return prevProgress + 10; } }); }, 500); // 发送上传请求 // axios.post('/api/upload', formData) // .then(() => { // clearInterval(timer); // setUploading(false); // }) // .catch(() => { // clearInterval(timer); // setUploading(false); // }); }; return ( <Upload name="file" action="/api/upload" showUploadList={false} beforeUpload={() => false} onChange={() => {}} customRequest={handleUpload} > <Button icon={<UploadOutlined />} disabled={uploading}> {uploading ? '上传中' : '点击上传'} </Button> {uploading && <UploadProgress percent={progress} />} </Upload> ); }; export default Demo; ``` 这段代码中,我们定义了一个`UploadProgress`组件作为自定义的进度组件,它接受一个`percent`属性用来表示上传进度的百分比。在`handleUpload`函数中,我们使用`setInterval`模拟上传进度,并使用`setProgress`函数更新上传进度。当上传进度达到100时,我们清除定时器并将`uploading`状态设置为`false`,表示上传完成。在`Upload`组件中,我们将`showUploadList`属性设置为`false`,禁用默认的上传列表,然后使用自定义的按钮和进度组件来替代默认的上传按钮和上传进度条。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值