在网站开发的某些情况下我们需要上传文件到服务器,在这个过程中可能会对文件做一定的限制,比如说文件格式,文件大小等,在一些情况下我们上传文件其实是为了获取其中的内容在前端区域展示,这个时候就不需要将文件上传到服务器,完全可以通过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>
 ...

效果图如下:
Javascript读取上传文件内容/类型/字节数

操作绑定,分别包含前端文件内容读取和文件上传

 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,
            })
          }
        })
    }
  }

如果看了上边的代码示例还搞不定欢迎留言提问!

相关文章:

  • 2022-12-23
  • 2021-09-25
  • 2021-05-18
  • 2021-11-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-29
猜你喜欢
  • 2022-12-23
  • 2021-11-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-23
  • 2021-08-05
相关资源
相似解决方案