记录:文件上传按钮

21 阅读1分钟

image.png

  renderUpload(label) {
    const { file, fileURL } = this.state
    return (
      <Col span={12}>
        <Form.Item label={label} {...formItemLayout} style={{ width: '100%' }}>
          <Button
            type="primary"
            style={{ marginRight: 15 }}
            onClick={() => this.selectFile()}
          >
            文件上傳
          </Button>
          <Button onClick={() => this.templateDownload()}>模板下載</Button>
          {file && (
            <div>
              <a href={fileURL} download={file.name} style={{ color: '#1890ff', fontSize: '14px', marginLeft: '10px', cursor: 'pointer' }}>
                上傳成功:{file.name}
              </a>
              <Button
                type="link"
                size="small"
                style={{ marginLeft: '10px', color: '#ff4d4f' }}
                onClick={() => this.removeFile()}
              >
                移除
              </Button>
            </div>
          )}
        </Form.Item>
      </Col>
    )
  }

点击文件上传:

  // 选择文件
  selectFile() {
    const _this = this;
    const fileInput = document.createElement("input");
    fileInput.type = "file";
    fileInput.accept = ".xlsx,.xls"; // 限制文件类型为 .xlsx 和 .xls
    fileInput.style.display = "none";
    document.body.appendChild(fileInput);
    const fileType = [
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xlsx
      "application/vnd.ms-excel" // .xls
    ];
    fileInput.addEventListener("change", function (event) {
      const file = event.target.files[0];
      if (file) {
        if (fileType.indexOf(file.type) === -1) {
          message.warning("上傳的文件類型不正確");
          return;
        }
        const fileURL = URL.createObjectURL(file);
        _this.setState({ file, fileURL });
        message.success('文件上傳成功')
        // 选择完文件后可移除这个临时的input元素
        console.log("file", file)
        fileInput.remove();
      }
    });
    // 触发文件輸入框的点击事件,打开文件选择对话框
    fileInput.click();
  }

移除文件:

  // 移除文件
  removeFile() {
    const { fileURL } = this.state;
    if (fileURL) {
      URL.revokeObjectURL(fileURL); // 释放之前创建的对象URL,回收内存
    }
    this.setState({
      file: '',
      fileURL: '',
    });
    message.success('文件已移除');
  }

提交:

image.png