antd upload 实现自定义文件上传

 1.Form表单文件

实现进度条,和存储数据

<Form.Item
   label=" "
   name={uploadName}
   rules={[{ required: arr.includes(isResponsibleQualification), message: "请上传文件" }]}>
       <Upload
           customRequest={uploadFile}
           listType="text"
           progress={{
                  format: percent => `${uploadPersent}%`
           }}
           defaultFileList={defaultFileList}>
             <Button type="primary" icon={<UploadOutlined />}>点击上传</Button>
      </Upload>
</Form.Item>
const [uploadPersent, setUploadPersent] = useState<number>(0)

const uploadFile = async (params: any) => {
        await uploadFileCustom(params, (data) => {
            console.log("data", data);
            params.onSuccess({
                url: data.picturePath,
                name: data.pictureRealName
            })
        }, (data) => {
            setUploadPersent(data)
        })
 }
export const uploadFileCustom = async (params: any, callback: (params: SuccessResponse) => void, progressCallback?: (uploadPercentage: number) => void) => {
    try {
        const { onSuccess, onError, file, onProgress } = params;
        let formData = new FormData();
        formData.append("files", file);
        const response: any = await POST<any>("/file/uploadFile", formData, {},
            {
                headers: { "content-type": "multipart/form-data" },
                onUploadProgress: (progressEvent: any) => {
                    const uploadPercentage = Math.round((progressEvent.loaded * 100) / 
                       progressEvent.total);
                    progressCallback && progressCallback(uploadPercentage)
                }
            }
        );
        if (response.code === 200) {
            callback(response.data)
        } else {
            message.error('上传失败')
        }
    } catch (e) {
        message.error('网络错误,上传失败!')
    }
}

返回的数据将存储在response中  

需要注意的是,在文件进行回显时,要进行setFieldsValue,和设置FormItem的defaultFileList才行

以下为defaultFileList的格式,

export const generateUploadFiles = (fileNowName: string="", fileName: string="") => {
    const files: any = []
    const urls = fileNowName.split(',')
    const names = fileName.split(',')
    urls.forEach((url, index) => {
        files.push({
            uid: url,
            name: names[index],
            status: 'done',
            response: {
                url: url,
                name: names[index]
            },
            url: `/api/file/getFile?storeName=${url}`,
        });
    });
    return files
}

 2.上线后发现点击文件进行下载后,本地无问题,上线后下载变为了跳转页面

对upload的默认下载进行修改

1.加入a标签 

2.upload加入api onPreview

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值