1

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!

  • Maybe you may call your function of `uploadAPP` behind another button. On choosing file you just save filename etc, and on uploading you do your POST activity. – Asma Mar 14 '23 at 08:10
  • Looks like you might want to watch for the change event on the form input and upload it then: https://stackoverflow.com/questions/3528359/html-input-type-file-file-selection-event – faire Mar 14 '23 at 08:11

3 Answers3

2

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} />
Crashh
  • 54
  • 8
1

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>
  );
Mallikarjun M G
  • 509
  • 4
  • 9
0

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

Leon1246
  • 13
  • 3