文件上传之前先进行预览

FileReader.readAsDataURL()

1.使用antd中的upload组件进行实现

        {
          avatarVisible
          && <Modal
          title="上传头像"
          visible={avatarVisible}
          onOk={this.onUpload}
          onCancel={this.onCancel}
          className={styles.modalBox}
          bodyStyle={{ height: 500 }}
          >
            <Upload
              name="avatar"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              beforeUpload={this.beforeUpload}
                  >
                <Button>
                   选择图片
                </Button>
            </Upload>
            <Row>
              <Col span={12}>
                <span>
                支持JPG、GIF、PNG格式,小于2M
                </span>
                 <div className={styles.leftContainer}>
                    {imageUrl ? <img src={imageUrl} alt="avatar" style={{  '100%' }} /> : null}
                 </div>
              </Col>
              <Col span={12}>
                  <span>效果预览</span>
                  <div className={styles.previewContainer}>
                      {imageUrl ? <img src={imageUrl} alt="avatar" style={{  '100%' }} /> : null}
                  </div>
              </Col>
            </Row>
          </Modal>
}

主要运用了beforeUpload方法,上传之前先获取file的属性并进行解析渲染

// 解析为base64位 
 getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
  // 读取文件 reader.readAsDataURL(img); } // 上传之前 beforeUpload
= file => { const { fileList } = this.state; this.getBase64(file, imageUrl => this.setState({ imageUrl, fileList: [...fileList, file], // loading: false, }), ); return false; }

再利用ajax请求,进行上传

onUpload = () => {
    const { fileList } = this.state;
    const formData = new FormData();
    fileList.forEach(file => {
      formData.append('files[]', file);
    });

    this.setState({
      // uploading: true,
    });
    // You can use any AJAX library you like
    request('https://www.mocky.io/v2/5cc8019d300000980a055e76', {
      method: 'post',
      processData: false,
      data: formData,
      success: () => {
        this.setState({
          fileList: [],
          // uploading: false,
        });
        message.success('upload successfully.');
      },
      error: () => {
        this.setState({
          // uploading: false,
        });
        message.error('upload failed.');
      },
    });
  };

2.使用js进行实现

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>单图片上传预览</title>
</head>
<body>
<div align="center">
<img width="400" height="250" id="xmTanImg"/><br/>
<input type="file" id="pic" name="pic" onchange="xmTanUploadImg(this)"/>
<input type="button" value="上传图片"/><br />
</div>
<script>
    //选择图片,马上预览
    function xmTanUploadImg(obj) {
        var file = obj.files[0];
          //file.size 单位为byte  可以做上传大小控制
        console.log("file.size = " + file.size);
        var reader = new FileReader();
        //读取文件过程方法
        reader.onloadstart = function (e) {
            console.log("开始读取....");
        }
        reader.onprogress = function (e) {
            console.log("正在读取中....");
        }
        reader.onabort = function (e) {
            console.log("中断读取....");
        }
        reader.onerror = function (e) {
            console.log("读取异常....");
        }
        reader.onload = function (e) {
            console.log("成功读取....");
            var img = document.getElementById("xmTanImg");
            img.src = e.target.result;
            //或者 img.src = this.result;  //e.target == this
        }
        reader.readAsDataURL(file)
    }
</script>
</body>
</html>
原文地址:https://www.cnblogs.com/jcxfighting/p/11449298.html