项目中遇到了一个上传的需求,看了一下已有的代码很粗糙,而且是直接引用andt的组件,体验不太好,自己使用FormData对象封装了一个上传组件,仅供参考。
代码如下:
/*** FileUploadModal* @description - 文件选择上传* @param data* @return {HTMLDivElement}* @author xxx*/FileUploadModal(props) {console.log("props", props)const { success } = propsconst [fileList, setFileList] = useState(null);const [isModalVisible, setIsModalVisible] = useState(false);const showModal = () => {setIsModalVisible(true);};const handleFileChange = ({ file, fileList: updatedFileList }) => {setFileList(updatedFileList);if (file.status === 'done') {message.success(`${file.name} file uploaded successfully.`);// 文件上传完毕后清空文件列表setFileList([]);}};// 文件导入const handleUpload = () => {// 在这里处理文件上传逻辑setIsModalVisible(false);console.log('文件已选择:', fileList);const formData = new FormData()formData.append('file', fileList[0].originFileObj)// 调用批量上传接口service.fetchUpload.call(formData, true).then((res) => {return res.json()}).then((res) => {setFileList([])if (res.resCode === 0) {message.success(`"上传成功"`)success()} else {message.success(`${res.resMsg}`)return}res?.hideIndicator?.()}).catch((err) => {console.log("err", err)ErrorPrompt.openErrorMessage(JSON.parse(err.response).resMsg)})};const handleCancel = () => {setFileList([])setIsModalVisible(false);};return (<><Button type="primary" onClick={showModal}>批量导入</Button><Modal title="批量文件导入" visible={isModalVisible}onOk={handleUpload}onCancel={handleCancel}><p>请选择文件进行上传</p><UploadbeforeUpload={() => false} // 禁止自动上传onChange={handleFileChange}rules={[{ required: true, message: "请上传文件" }]}valuePropName="fileList"getValueFromEvent={e=>{if(Array.isArray(e)) return e; return e && e.fileList}}fileList={fileList}><Button>选择文件</Button></Upload></Modal></>);},
使用更简单,因为把触发modal的按钮也封装在组件里了,直接引用即可:
<FileUploadModal success={() => { //callback functionxxxRef.current.fetchData()xxxRef.current.setState({selectedRows: [],selectedRowKeys: [],})
}}/>
转载请注明出处