Advertisement
Guest User

ImageDisplayReact

a guest
Feb 18th, 2020
1,794
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ImageDisplay.js
  2. import React, { useState } from 'react';
  3. import axios from 'axios';
  4.  
  5. export default function ProfileImage() {
  6.    const [values, setValues] useState({
  7.       imagePreviewUrl: "",
  8.       picFile: null
  9.    })
  10.    let fileInput = React.createRef();
  11.    
  12.    // Activates user file input to set div
  13.    const editProfilePic = () => {
  14.       fileInput.current.click();
  15.    }
  16.    // Handles the image that was input by user
  17.    const handleImageChange = e => {
  18.       e.preventDefault();
  19.       let reader = new FileReader();
  20.       let inFile = e.target.files[0];
  21.       reader.onloadend = () => {
  22.          setValues({...values,
  23.             picFile: inFile,
  24.             imagePreviewUrl: reader.result
  25.          })
  26.       };
  27.       reader.readAsDataURL(inFile);
  28.    };
  29.  
  30.    // Call the API Backend, will describe this later
  31.    const handleSubmit = async() => {
  32.       // response stores the response back from the API
  33.       response = await axios.post(`/storage/upload`,form_data)
  34.       .catch(error => {
  35.          alert("Error occurred while uploading picture, try uploading a smaller image size or try again later.")
  36.          return;
  37.       });
  38.    }
  39.  
  40.  
  41.    return(
  42.    <div>
  43.       <div onClick={() => editProfilePic()}>
  44.         <input
  45.            type="file"
  46.            accept="image/*"
  47.            onChange={handleImageChange}
  48.            ref={fileInput} />
  49.         <img
  50.            src={imagePreviewUrl}
  51.            alt="..." style={{objectFit: 'cover'}}/>
  52.       </div>
  53.       <button onClick={handleSubmit}>Submit<button />
  54.    </div>
  55.    )
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement