前言
在實(shí)現(xiàn)圖片上傳時(shí),可能需要用到Upload,但是它默認(rèn)的上傳方式是加入圖片后直接上傳,如果要實(shí)現(xiàn)最后再一次性上傳,需要自定義內(nèi)容。


//添加按鈕的樣式const uploadButton = ( <div> <Icon type="plus" /> <div className="ant-upload-text">Upload</div> </div> );<Upload //樣式 className={styles['override-ant-btn']} //陳列樣式,現(xiàn)在是卡片式 listType="picture-card" //再圖片上傳到頁面后執(zhí)行的函數(shù),自定義讓他不執(zhí)行 beforeUpload={() => false} //數(shù)據(jù),即圖片,是一個(gè)數(shù)組 fileList={fileList} //當(dāng)點(diǎn)擊查看時(shí)調(diào)用(上圖的那個(gè)眼睛) onPreview={this.handlePreview} //數(shù)據(jù)改變時(shí)調(diào)用 onChange={this.handleChange} > //當(dāng)不少于一張圖時(shí),不顯示怎加圖片的按鈕。 {fileList.length >= 1 ? null : uploadButton} </Upload>還有一個(gè)移除時(shí)調(diào)用的函數(shù)onRemove(),即點(diǎn)擊上圖的垃圾桶,這里沒有定義。
handlePreview = (file) => { this.setState({ previewImage: file.url || file.thumbUrl, visible: true, }); }; <Modal visible={visible} footer={null} onCancel={this.handleCancel}> <img alt="加載" style={{ width: '100%',height: '100%' }} src={previewImage} /> </Modal>利用Modal顯示圖片。
handleChange = ({ fileList }) => { this.setState({ fileList });};數(shù)據(jù)改變時(shí)直接重設(shè)fileList數(shù)組的值(我這里只有一張圖可以這么做)。
最后是fileList的一些基本設(shè)置:
fileList: [{ uid: 'id', name: '標(biāo)題', //目前的狀態(tài) status: 'done', //圖片的url或者base64 url: '', type: 'image/jpeg', }],PS:基于antd的上傳文件進(jìn)度條
核心代碼
//通過前端原生XMLHttpRequest動(dòng)態(tài)獲取上傳文件進(jìn)度doTransferFile = (file) => { let mySelf = this; let formData = new FormData(); let url = "http://xxx:444/upload_file.php"; let file = document.getElementById("chooseFile").files[0]; console.log(file) formData.append("file",file); // console.log(modal); // console.log(formData); // return false; /* eslint-disable */ $.ajax({ url : url, type : 'POST', enctype: 'multipart/form-data', data : formData, // 告訴jQuery不要去處理發(fā)送的數(shù)據(jù) processData : false, // 告訴jQuery不要去設(shè)置Content-Type請求頭 contentType : false, timeout : 60000,//設(shè)置超時(shí)時(shí)間 beforeSend:function(){ console.log("現(xiàn)在開始上傳文件!"); notification['info']({ message: '提示', description: '現(xiàn)在開始上傳文件!', }); }, xhr: function(){ let myXhr = $.ajaxSettings.xhr(); // console.log(myXhr) if(myXhr.upload){ myXhr.upload.addEventListener('progress',function(e) { if (e.lengthComputable) { let percent = Math.floor((e.loaded/e.total)*100); // console.log(e.loaded) // console.log(e.total) console.log(percent) let upload = mySelf.state.upload; upload.progress.loaded = e.loaded; upload.progress.total = e.total; upload.progress.percentage = percent; mySelf.state.upload = upload; // console.log(info); mySelf.setState({ upload: upload }); } },false); myXhr.upload.addEventListener('load',function(e) { console.log('fish') },false); } return myXhr; }, success : function(res) { console.log(res) }, error : function(res) { } });};在antd框架下,調(diào)用的Progress組件動(dòng)態(tài)展示的上傳文件進(jìn)度,效果圖如下,待全部上傳成功后,由接口返回上傳文件的大小,路徑等信息,render到頁面上
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答