在網(wǎng)站開(kāi)發(fā)的某些情況下我們需要上傳文件到服務(wù)器,在這個(gè)過(guò)程中可能會(huì)對(duì)文件做一定的限制,比如說(shuō)文件格式,文件大小等,在一些情況下我們上傳文件其實(shí)是為了獲取其中的內(nèi)容在前端區(qū)域展示,這個(gè)時(shí)候就不需要將文件上傳到服務(wù)器,完全可以通過(guò)Javascript來(lái)獲取上傳文件內(nèi)容然后進(jìn)行展示,既加快了操作速度,也減輕了服務(wù)器的負(fù)載和存儲(chǔ)。接下來(lái)就是一個(gè)實(shí)際操作的過(guò)程:
首先來(lái)看一下一個(gè)上傳文件對(duì)象的屬性:
UI設(shè)計(jì)(React+Material-ui)
... const styles = theme => ({ formControl: { margin: theme.spacing.unit, minWidth: 120, width: '100%', }, leftIcon: { marginRight: theme.spacing.unit, } }) ... <Grid item xs> <FormControl className={classes.formControl} error={this.state.Err.includes('sqlStr')} > <TextField label="SQL" onChange={this.onTextChange('sqlStr')} value={this.state.sqlStr} placeholder="Add Select SQL here..." multiline InputLabelProps={{ shrink: true, }} fullWidth rows={6} variant="outlined" /> <FormHelperText>{this.state.sqlStrErr}</FormHelperText> <input style={{display: 'none'}} name="uploadSqlFile" id="uploadSqlFile" onChange={this.handleUploadSqlFile} type="file" /> <label htmlFor="uploadSqlFile" style={{position: 'absolute', right: '0px',bottom: '20px', background:'#f5f0ff'}}> <Button color="primary" variant="outlined" component="span"> <CloudUploadOutlined className={classes.leftIcon} />OR UPLOAD SQL FILE </Button> </label> </FormControl> </Grid> ...
效果圖如下:
操作綁定,分別包含前端文件內(nèi)容讀取和文件上傳
handleUploadSqlFile = event => { let that = this const selectedFile = event.target.files[0] if(selectedFile.type.includes('text') || selectedFile.type === ''){ let reader = new FileReader();// !important reader.readAsText(selectedFile, "UTF-8");// !important reader.onload = function(evt){// !important let sqlStr = evt.target.result;// !important that.setState({ Err: that.state.Err.filter(c => c !== 'sqlStr'), sqlStr: sqlStr, sqlStrErr: '*Avoid duplicated column fields', }) } }else { let sqlStrErr = 'File format is not supported!' if ((selectedFile.size / 1024 / 1024).toFixed(4) >= 2) {//計(jì)算文件大小并且換算成M為單位 sqlStrErr = 'File size exceeds the limitation (2M)!' } this.setState({ Err: [...this.state.Err, 'sqlStr'], sqlStrErr: sqlStrErr }) } }
上邊的示例只是單純的前端文件內(nèi)容讀取,并未涉及文件上傳到服務(wù)器,接下來(lái)是:
import axios from 'axios' ... handleUploadSqlFile = event => { const selectedFile = event.target.files[0] if ((selectedFile.size / 1024 / 1024).toFixed(4) >= 10) { this.setState({ sqlStrErr: 'File size exceeds the limitation (10M)!' }) } else { const data = new FormData() data.append('file', selectedFile, selectedFile.name) axios .post('/api/utils/upload_file', data, { onUploadProgress: ProgressEvent => { this.setState({ loaded: (ProgressEvent.loaded / ProgressEvent.total) * 100 - Math.random() * 16,//此值用來(lái)展示上傳進(jìn)度,好讓用戶知道目前的上傳狀態(tài)。 }) }, }) .then(res => { if (res.data.code === -1) { this.setState({ sqlStrErr: res.data.info }) } else { this.setState({ loaded: 100, }) } }) } }
如果看了上邊的代碼示例還搞不定歡迎留言提問(wèn)!
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com