Home > Software design >  How to get progressbar when file upload to browser
How to get progressbar when file upload to browser

Time:11-16

How to get file uploading percentage when file uploading from client file system to client's browser.

I have the simplest form. I need to get file uploading percentage and show it to user when he upload file.

export default function App() {
  const handleSubmit = (e) => {
    e.preventDefault();

    console.log("submit");
  };
  return (
    <div className="App">
      <form onSubmit={handleSubmit}>
        <input type="file" />
        <input type="submit" value="click to submit" />
      </form>
    </div>
  );
}

Demo

CodePudding user response:

here is small example, with react bootsttrap you can try, you have to import,

import { Container, Row, Col, Form, Button, ProgressBar } from "react-bootstrap"

your javascript logic will be like this, ProgressBar needs % percentage value, you can calculate that,

const [selectedFiles, setSelectedFiles] = useState()
const [progress, setProgress] = useState()

const handleSubmit = e => {
  e.preventDefault() //prevent the form from submitting
  let formData = new FormData()

  formData.append("file", selectedFiles[0])

  const axios = axios.create({
    baseURL: "http://localhost:8080/",
  })

  axios.post("/upload_file", formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
    onUploadProgress: data => {
      //Set the progress value to show the progress bar
      setProgress(Math.round((100 * data.loaded) / data.total))
    },
  })
}

here is component return will look like,

<Form
  action="http://localhost:8081/upload_file"
  method="post"
  encType="multipart/form-data"
  onSubmit={handleSubmit}
>
  <Form.Group>
    <Form.File
      label="Select a File"
      onChange={e => {
        setSelectedFiles(e.target.files)
      }}
    />
  </Form.Group>
  <Form.Group>
    <Button variant="info" type="submit">
      Upload A File
    </Button>
  </Form.Group>
  {progress && <ProgressBar now={progress} label={`${progress}%`} />}
</Form>
  • Related