Upload to S3 from Client Example


  • administrators

    import React from "react";
    import { withApollo } from "react-apollo";
    // import S3FileUpload from "react-s3";
    import S3 from "aws-s3";
    // import { Link } from "react-router-dom";
    
    // material-ui icons
    // import Assignment from "@material-ui/icons/Assignment";
    import CloudUploadIcon from "@material-ui/icons/CloudUpload";
    // core components
    
    import Button from "components/CustomButtons/Button.jsx";
    
    // @material-ui/core components
    import withStyles from "@material-ui/core/styles/withStyles";
    
    // core components
    import FormControl from "@material-ui/core/FormControl";
    import regularFormsStyle from "assets/jss/material-dashboard-pro-react/views/regularFormsStyle";
    
    import { GET_SECRET } from "../../graphql/User";
    import { CHECK_FILE } from "../../graphql/FileManager";
    import { RUN } from "../../graphql/Command";
    
    import config from "../../config";
    
    class Upload extends React.Component {
      state = {
        awsS3Config: {}
      };
      handleChangeFile = async event => {
        console.log(this.state.awsS3Config);
        const file = event.target.files[0];
        console.log(file);
        const fileName = file.name.trim().replace(/[^a-zA-Z0-9.]+/g, "-");
        //8233-2.jpg
        const newFileName = fileName
          .split(".")
          .slice(0, -1)
          .join(".");
        //8233-2;
    
        const newFile = new File([file], fileName, { type: file.type });
        const S3Client = new S3({
          ...this.state.awsS3Config,
          s3Url: config.s3.BASE_URL
        });
        S3Client.uploadFile(newFile, newFileName)
          .then(async res => {
            // console.log(res);
            let fileUrl = res.location;
            if (config.s3.COULD_URL) {
              fileUrl = fileUrl.replace(config.s3.BASE_URL, config.s3.COULD_URL);
            }
            const filePath = res.key;
    
            if (process.env.REACT_APP_N_ENV === "stage") {
              const { data } = await this.props.client.query({
                query: CHECK_FILE,
                variables: { fileUrl: fileUrl }
              });
              // console.log(data);
              const fileExist = data.checkFile;
              if (fileExist) {
                await this.props.client.query({
                  query: RUN,
                  variables: { command: "invalidate", filePath: filePath }
                });
              }
            }
            this.props.handleFileUploaded({
              url: fileUrl,
              size: file.size,
              fileType: file.type
            });
          })
          .catch(err => console.log(err));
        //Make a request to server and send formData
      };
    
      async componentDidMount() {
        const { data } = await this.props.client.query({
          query: GET_SECRET,
          fetchPolicy: "network-only",
          variables: { secretId: config.awsS3 }
        });
        this.setState({
          awsS3Config: JSON.parse(data.getSecret)
        });
      }
    
      render() {
        const { classes } = this.props;
        return (
          <FormControl>
            <input
              className={classes.input}
              id="contained-button-file"
              multiple
              type="file"
              onChange={this.handleChangeFile}
              style={{ display: "none" }}
            />
            <label htmlFor="contained-button-file">
              <Button variant="contained" component="span">
                Upload <CloudUploadIcon className={classes.rightIcon} />
              </Button>
            </label>
          </FormControl>
        );
      }
    }
    
    export default withApollo(withStyles(regularFormsStyle)(Upload));