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
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
Just include a change event handler on your input field
in your component implement:
The block will get executed onchanges in the file input field trigger by files attached/inputted
You can trigger
upload
inonChangeHandler
itselfIn JSX