skip to Main Content

I am trying to upload some files using ReactJS, but I want my UI to only have a single "Upload" button instead of two "choose file" and "upload" button. Here is the code:

import React, { useRef } from 'react';
import Button from '@mui/material/Button';

function Filesubmit() {
  const fileInput = useRef(null);

  async function handleSubmit(event) {
    event.preventDefault();
    await getSignedUrl();
  }

  async function getSignedUrl() {
    //  prepare the post request
    ....
    const fname = JSON.stringify({ app: fileInput.current.files[0].name });
    ....
      uploadAPP(url, key, keyID, secToken, policy, signature, fileInput.current.files[0]);
  }

  async function uploadAPP(url_, key_, keyID_, secToken_, policy_, signature_, appFile_) {
    const formdata = new FormData();
    formdata.append('key', key_);
    .....

    const requestOpts = {
      method: 'POST',
      body: formdata,
      redirect: 'follow',
    };
     .....
    }
  }

  return (
    <div className="card">
      <form onSubmit={handleSubmit}>
        <input type="file" ref={fileInput} />
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

export default Filesubmit;

How do I build the "Upload" button to handle both the things?

Any help regarding this will be appreciated!

3

Answers


  1. Just use the onChange event, so when the user upload a file he dont need to press the button for submitting it. Also if you want to display some information you could use a label for the input

    <input type="file" ref={fileInput} onChange={handleChange} />
    
    Login or Signup to reply.
  2. Just include a change event handler on your input field

     <input type="file" (change)="onChange($event)"/>
    

    in your component implement:

        onChange(event: Event){
        const target = event.target as HTMLInputElement;
        this.files = (target.files as FileList)[];  
    
         //do whatever you want with the files
        }
    

    The block will get executed onchanges in the file input field trigger by files attached/inputted

    Login or Signup to reply.
  3. You can trigger upload in onChangeHandler itself

    const onChange = (e) => {
        const fname = e.target.files[0].name;
        uploadAPP(
          url,
          key,
          keyID,
          secToken,
          policy,
          signature,
          e.target.files[0]
        );
      };
    
    

    In JSX

    return (
        <div className="card">
            <input type="file" onChange={onChange} ref={fileInput} />
        </div>
      );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search