本篇内容主要讲解“Javascript怎么读取上传文件内容/类型/字节数”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Javascript怎么读取上传文件内容/类型/字节数”吧!
首先来看一下一个上传文件对象的属性:
UI设计(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> ...
效果图如下:
操作绑定,分别包含前端文件内容读取和文件上传
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) {//计算文件大小并且换算成M为单位 sqlStrErr = 'File size exceeds the limitation (2M)!' } this.setState({ Err: [...this.state.Err, 'sqlStr'], sqlStrErr: sqlStrErr }) } }
上边的示例只是单纯的前端文件内容读取,并未涉及文件上传到服务器,接下来是:
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,//此值用来展示上传进度,好让用户知道目前的上传状态。 }) }, }) .then(res => { if (res.data.code === -1) { this.setState({ sqlStrErr: res.data.info }) } else { this.setState({ loaded: 100, }) } }) } }
到此,相信大家对“Javascript怎么读取上传文件内容/类型/字节数”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。