带有文件上传的语义UI React进度栏

时间:2019-04-09 18:30:00

标签: reactjs semantic-ui

我有一个小的文件上传组件,用户可以在其中从文件系统中选择一个文件并上传(通过REST调用发送)。

我正在尝试从语义UI反应实现<Progress>模块,以在文件发送到端点时指示成功/失败。那么最好根据响应的status来执行此操作吗?还是有更好的方法来处理它?<​​/ p>

Codesandbox是here

    class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          file: null,
          fileName: "",
          isUploading: false,
          statusCode: ""
        };
      }

      onFormSubmit = e => {
        e.preventDefault(); // Stop form submit
        this.fileUpload(this.state.file).then(response => {
          console.log(response.data);
        });
      };

      fileChange = e => {
        this.setState(
          { file: e.target.files[0], fileName: e.target.files[0].name },
          () => {
            console.log(
              "File chosen --->",
              this.state.file,
              console.log("File name  --->", this.state.fileName)
            );
          }
        );
      };


  fileUpload = async file => {
    const formData = new FormData();
    formData.append("file", file);
    try {
      axios.post("/file/upload/enpoint").then(response => {
        console.log(response);
        console.log(response.status);
        this.setState({ statusCode: response.status }, () => {
          console.log(
            "This is the response status code --->",
            this.state.statusCode
          );
        });
      });
    } catch (error) {
      console.error(Error(`Error uploading file ${error.message}`));
    }

    const data = JSON.stringify({
      uploadData: file
    });
    console.log(data);
  };

  render() {
    const { statusCode } = this.state;
    const panes = [
      {
        menuItem: "Import ",
        render: () => (
          <Tab.Pane attached={false}>
            <Message>Some random message idk.</Message>
            <Form onSubmit={this.onFormSubmit}>
              <Form.Field>
                <label>File input & upload </label>
                <Button as="label" htmlFor="file" type="button" animated="fade">
                  <Button.Content visible>
                    <Icon name="file" />
                  </Button.Content>
                  <Button.Content hidden>Choose a File</Button.Content>
                </Button>
                <input
                  type="file"
                  id="file"
                  hidden
                  onChange={this.fileChange}
                />
                <Form.Input
                  fluid
                  label="File Chosen: "
                  placeholder="Use the above bar to browse your file system"
                  readOnly
                  value={this.state.fileName}
                />
                <Button style={{ marginTop: "20px" }} type="submit">
                  Upload
                </Button>
                {statusCode && statusCode === "200" ? (
                  <Progress
                    style={{ marginTop: "20px" }}
                    percent={100}
                    success
                    active
                    progress
                  />
                ) : statusCode && statusCode === "500" ? (
                  <Progress
                    style={{ marginTop: "20px" }}
                    percent={100}
                    error
                    active
                    progress
                  />
                ) : null}
              </Form.Field>
                </Form>
              </Tab.Pane>
            )
          }
        ];
        return (
          <Segment style={{ padding: "5em 1em" }} vertical>
            <Divider horizontal>OFFLINE USAGE</Divider>
            <Tab menu={{ pointing: true }} panes={panes} />
          </Segment>
        );
      }
    }

2 个答案:

答案 0 :(得分:1)

我有一个建议的解决方案,主要针对减速器。您要做的就是必须分派加载操作。

转到我的Github存储库:Semantic UI Indicator

您将可以浏览该存储库并了解这一点。这只是一种不同的方法。因此,可以有很多方法可以做到这一点。我使用了一个简单的语义加载程序,以防您可以将相同的内容应用于进度条。

答案 1 :(得分:0)

我更改了fileUpload函数,从服务器响应中使用statusCode更新了response.status状态变量。

  fileUpload = async file => {
    const formData = new FormData();
    formData.append("file", file);
    try {
      axios.post("/file/upload/enpoint").then(response => {
        console.log(response);
        console.log(response.status);
        this.setState({ statusCode: response.status }, () => {
          console.log(
            "This is the response status code --->",
            this.state.statusCode
          );
        });
      });
    } catch (error) {
      console.error(Error(`Error uploading file ${error.message}`));
    }
  };

然后在渲染中,我检查了statusCode200还是500,我将其更改为包括更合适的状态代码,但您明白了。

{statusCode && statusCode === 200 ? (
                  <Progress
                    style={{ marginTop: "20px" }}
                    percent={100}
                    success
                    progress
                  >
                    File Upload Success
                  </Progress>
                ) : statusCode && statusCode === 500 ? (
                  <Progress
                    style={{ marginTop: "20px" }}
                    percent={100}
                    error
                    active
                    progress
                  >
                    File Upload Failed
                  </Progress>
                ) : null}

here为想要看的人提供了更新的代码和框。