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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com

《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线

暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。

艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。

《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。