aws-amplify#Storage JavaScript Examples

The following examples show how to use aws-amplify#Storage. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: App.js    From react-admin-amplify-demo with MIT License 6 votes vote down vote up
// Get the demo user avatar
authProvider.getIdentity = async () => {
  try {
    const userData = await API.graphql(
      graphqlOperation(queries.getUser, { id: "demo" })
    );

    const url = await Storage.get(userData.data.getUser.picture.key);

    return {
      id: "demo",
      fullName: "Demo",
      avatar: url,
    };
  } catch (e) {
    console.log(e);
  }
};
Example #2
Source File: SynonymsForm.js    From vch-mri with MIT License 6 votes vote down vote up
componentDidMount() {
        this.setState({ loading: true });
        Storage.get('thesaurus.ths', {
            download: true,
            expires: 1
        })
            .then(data => {
                data.Body.text().then(string => {
                    let synonymStrings = string.split(/[\r\n]+/);
                    let synonyms = synonymStrings.map((s) => {
                        let words = s.split(' : ');
                        return {word: words[0], synonym: words[1]}
                    });

                    let fileStrings = synonyms.map((s) => [s.word, s.synonym].join(" : "));
                    let fileString = fileStrings.join("\n");
                    console.log(fileString);

                    console.log(synonyms);
                    this.setState({
                        fileContents: string,
                        synonyms: synonyms
                    })
                });
            })
            .catch(err => {
                console.log('error getting the thesaurus file')
            })
            .finally(() => this.setState({ loading: false }));
    }
Example #3
Source File: SynonymsForm.js    From vch-mri with MIT License 6 votes vote down vote up
handleSubmit(e) {
        e.preventDefault();
        this.setState({ loading: true });

        Storage.put('thesaurus.ths', this.state.fileContents, {
            level: 'public'
        })
            .then (result => {
                console.log(result);
                sendSuccessToast('Synonyms have been successfully updated!');
            })
            .catch(e => {
                console.log(e);
                sendErrorToast(e.message);
            })
            .finally(() => this.setState({ loading: false }));
    }
Example #4
Source File: CCPData.js    From aws-amplify-connect with MIT No Attribution 6 votes vote down vote up
async onChange(e) {
      const file = e.target.files[0];
      console.log(file)
      this.setState({filename: file.name})
      const localthis = this;
      await Storage.put(("csvupload/" + file.name), file, {
        level: 'public',
        contentType: file.type,
        //customPrefix: "csvupload",
        progressCallback(progress) {
          var currentpercent = Math.round(progress.loaded/progress.total*100)
          localthis.setState({percent: currentpercent})
          console.log('Uploading:' + localthis.state.percent)
        },
      }).then (result => {
        this.setState({result: 
          <Message success>
          <Message.Header>Uploaded</Message.Header>
          <p>{this.state.filename}</p>
        </Message>
        })
        console.log(result)
        }
      ).catch(err => {
        this.setState({result: 
        <Message negative>
          <Message.Header>Error whilst uploading</Message.Header>
          <p>{this.state.filename}</p>
        </Message>
        })
        console.log(err)
        }
      );
  }
Example #5
Source File: S3Store.js    From aws-perspective with Apache License 2.0 6 votes vote down vote up
uploadObject = async (key, content, level, type) => {
  return Storage.put(key, content, {
    level: level,
    contentType: type,
    metadata: {
      username: `${await Auth.currentAuthenticatedUser().then(
        (response) => response.username
      )}`,
    },
  });
}
Example #6
Source File: S3Store.js    From aws-perspective with Apache License 2.0 6 votes vote down vote up
uploadTemplate = async (key, content, type) => {
  return Storage.put(key, content, {
    acl: 'public-read',
    contentType: type,
    metadata: {
      username: `${await Auth.currentAuthenticatedUser().then(
        (response) => response.username
      )}`,
    },
  });
}
Example #7
Source File: S3Store.js    From aws-perspective with Apache License 2.0 6 votes vote down vote up
getObject = async (key, level) => {
  return await Storage.get(key, { level: level })
    .then((result) => {
      return fetch(result)
        .then((response) => response.json())
        .catch((err) => err);
    })
    .catch((err) => err);
}
Example #8
Source File: App.js    From Osiris with MIT License 5 votes vote down vote up
function App() {
  const { globalState, dispatch } = React.useContext(Context);

  const handlePromises = (itemsFromDB) => {
    const uiItemsPromises = itemsFromDB.map((obj) => {
      return Storage.get(`${obj.file_name}.jpg`);
    });
    Promise.all(uiItemsPromises).then((results) => {
      // combining itemsFromDB with their appropriate urls
      const updateUiItems = itemsFromDB.map((item, index) => {
        item.url = results[index];
        return item;
      });

      dispatch({ type: "add_uis", payload: updateUiItems });
    });
  };

  useEffect(() => {
    pool.query("SELECT * FROM individual_ui").then((data) => {
      handlePromises(data.rows);
    });
  }, []);

  return (
    <Context.Consumer>
      {({ globalState }) => (
        <Router>
          <div className="navbar">
            <img
              src="https://i.imgur.com/HM3EwJ5.jpg"
              className="logo"
              alt="osiris"
              width="180"
              height="180"
            />
            <ul>
              <li>
                <Link to="/">UI Library</Link>
              </li>
              <li>
                <Link to="/generator">UI Generator</Link>
              </li>
              <li>
                <Link to="/buildpage">Build Page</Link>
              </li>
            </ul>
          </div>
          <Switch>
            <Route exact path="/">
              <UiLibrary page="uilibrary" buttonText="Details" />
            </Route>
            <Route exact path="/generator">
              <Generator />
            </Route>
            <Route exact path="/detailPage">
              <DetailPage />
            </Route>
            <Route exact path="/buildpage">
              <BuildPage />
            </Route>
            <Route render={() => <Redirect to="/" />} />
          </Switch>
        </Router>
      )}
    </Context.Consumer>
  );
}
Example #9
Source File: S3Store.js    From aws-perspective with Apache License 2.0 5 votes vote down vote up
listObjects = (key, level) => {
  return Storage.list(key, { level: level });
}
Example #10
Source File: S3Store.js    From aws-perspective with Apache License 2.0 5 votes vote down vote up
removeObject = (key, level) => {
  return Storage.remove(key, { level: level });
}
Example #11
Source File: S3Store.js    From aws-perspective with Apache License 2.0 5 votes vote down vote up
removeObjects = async (keys, level) =>
  Promise.all(
    keys.map(async (key) => await Storage.remove(key, { level: level }))
  )
Example #12
Source File: S3Store.js    From aws-perspective with Apache License 2.0 5 votes vote down vote up
generatePreSignedURL = (key, expires) => {
  return Storage.get(key, { expires: expires });
}
Example #13
Source File: S3Store.js    From aws-perspective with Apache License 2.0 5 votes vote down vote up
Storage.configure(window.amplify.Storage);
Example #14
Source File: ScreenSharing.js    From allscreens with GNU General Public License v3.0 5 votes vote down vote up
_startCapturing(e) {
        console.log('Start capturing.');

        this.setState({
            status: 'Screen recording started.',
            enableStartCapture: false,
            enableStopCapture: true
        });

        if (this.state.recording) {
            window.URL.revokeObjectURL(this.state.recording);
        }

        this.setState({
            chunks: [],
            recording: null
        });

        ScreenSharing._startScreenCapture()
            .then(stream => {
                stream.addEventListener('inactive', e => {
                    console.log('Capture stream inactive - stop recording!');
                    this._stopCapturing(e);
                });

                this.screen.current.srcObject = stream;
                this.setState({
                    stream: stream
                });

                this.timer = setInterval(() => {

                    if (this.state.ticket !== null) {
                        const now = new Date();
                        const endDate = new Date(this.state.ticket.activeUntil);
                        const withValidTicket = (endDate.getTime() - now.getTime()) > 0;
                        console.log("withValidTicket", withValidTicket);
                        if (!withValidTicket) return;

                        let canvas = document.createElement("canvas");
                        let video = this.screen.current;
                        canvas.width = video.videoWidth;
                        canvas.height = video.videoHeight;
                        canvas.getContext('2d').drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
                        this.imageView.current.setAttribute('src', canvas.toDataURL());

                        Storage.put("upload/" + this.state.ticket.email + "/screenshot.txt", canvas.toDataURL())
                            .then(result => console.log(result))
                            .catch(err => console.log(err));
                    }


                    // let apiName = 'screenshotapi'; // replace this with your api name.
                    // let path = '/screenshots'; //replace this with the path you have configured on your API
                    // let myInit = {
                    //     body: { dataUrl: canvas.toDataURL() }, // replace this with attributes you need
                    //     headers: { 'Content-Type': 'application/json' }
                    // };

                    // API.post(apiName, path, myInit).then(response => {
                    //     // Add your code here
                    //     console.log(response);
                    // }).catch(error => {
                    //     console.log(error.response);
                    // });

                }, 5000);
            });

    }
Example #15
Source File: Generator.jsx    From Osiris with MIT License 4 votes vote down vote up
function Generator(props) {
	const { dispatch } = React.useContext(Context);
	// initial state for generator:
	// htmlTags, buttonText, placeholder - compiled into react code
	// file only for handleFileChange
	const [ userData, setUserData ] = useState({
		htmlTags: 'div',
		searchTags: '',
		reactCode: '',
		description: '',
		fileName: '',
		buttonText: '',
		placeholder: '',
		image: '',
		s3file: '',
		fontColor: '',
		fontWeight: '',
		fontFamily: '',
		fontStyle: '',
	});

	// uploading files
	function handleFileChange(e) {
		const file = e.target.files[0];
		const reader = new FileReader();
		const imgtag = document.getElementById('imageupload');
		imgtag.title = file.name;

		reader.onload = function(event) {
			imgtag.src = event.target.result;
		};

		reader.readAsDataURL(file);
		setUserData({
			...userData,
			s3file: file
		});
	}

	// typed input updating state
	function handleChange(e) {
		setUserData({
			...userData,
			[e.target.name]: e.target.value
		});
	}

	//
	async function handleClick(e) {
		e.preventDefault();
		try {
			let image = await Storage.put(`${userData.fileName}.jpg`, userData.s3file);

			const { htmlTags, buttonText, placeholder, searchTags, description, fileName } = userData;

			let reactCode;

			switch (htmlTags) {
				case 'button':
					reactCode = `<${htmlTags} style={}></${htmlTags}>`;
					break;
				case 'input':
					reactCode = `<${htmlTags} placeholder=${placeholder}></${htmlTags}>`;
					break;
				case 'h1':
					reactCode = `<${htmlTags} style={}></${htmlTags}>`;
					break;
				case 'h2':
					reactCode = `<${htmlTags} style={}></${htmlTags}>`;
					break;
				case 'h3':
					reactCode = `<${htmlTags} style={}></${htmlTags}>`;
					break;
				case 'p':
					reactCode = `<${htmlTags} style={}></${htmlTags}>`;
					break;
				case 'ul':
					reactCode = `<${htmlTags} style={}></${htmlTags}>`;
					break;
				case 'li':
					reactCode = `<${htmlTags} style={}></${htmlTags}>`;
					break;
				case 'img':
					reactCode = `<${htmlTags} alt='' src='' style={}/>`;
					break;
				default:
					reactCode = `<${htmlTags}></${htmlTags}>`;
					break;
			}

			// send new data to database
			pool
				.query(
					'INSERT INTO individual_ui(tags, react_code, file_name, type, description) VALUES($1, $2, $3, $4, $5 )',
					[ searchTags, reactCode, fileName, htmlTags, description ]
				)
				.then((data) => {
					// update the global state/Context
					pool.query('SELECT * FROM individual_ui').then((data) => {
						let item = data.rows[data.rows.length - 1]; // just added item
						Storage.get(`${item.file_name}.jpg`).then((url) => {
							item.url = url;
							dispatch({
								type: 'generator_add_details',
								payload: {
									item: item
								}
							});
							props.history.push('/detailPage');
						});
					});
				})
				.catch((err) => console.log(err));
		} catch (err) {
			console.warn(err);
		}
	}

	return (
		<div className="generator-container">
			<div className="genHead">
				<h1 className="heading-generator">UI Generator</h1>
			</div>
			<div className="top-container">
				<input type="file" accept="image/x-png,image/gif,image/jpeg" onChange={handleFileChange} />
				<div className="image-container">
					<img id="imageupload" src="" />
				</div>
			</div>
			<div className="bottom-container">
				<form onSubmit={handleClick}>
					<select id="type" onChange={handleChange} defaultValue="1" name="htmlTags">
						<option value="div">Div</option>
						<option value="button">Button</option>
						<option value="input">Input</option>
						<option value="h1">H1</option>
						<option value="h2">H2</option>
						<option value="h3">H3</option>
						<option value="p">Paragraph</option>
						<option value="ul">Navbar</option>
						<option value="li">List Item</option>
						<option value="img">Image</option>
					</select>
					{userData.htmlTags === 'input' && (
						<input
							name="placeholder"
							placeholder="Input Text"
							onChange={handleChange}
							value={userData.placeholder}
						/>
					)}
					<input
						name="searchTags"
						placeholder="Search Tag Name"
						onChange={handleChange}
						value={userData.searchTags}
					/>
					<input name="fileName" placeholder="File Name" onChange={handleChange} value={userData.fileName} />
					<input
						name="description"
						placeholder="Description"
						onChange={handleChange}
						value={userData.description}
					/>
					<button className="submitButton" type="submit">
						Submit
					</button>
				</form>
			</div>
		</div>
	);
}