user3708761
user3708761

Reputation: 275

Getting the size of an uploaded file React JS

How would I go about finding the size of an uploaded file in React JS?

Upvotes: 8

Views: 28178

Answers (3)

Plabon Dutta
Plabon Dutta

Reputation: 7249

Let's say, your jsx is like <input type="file" onChange={this.fileChangedHandler}/>

Now, in your fileChangedHandler, you'll have to do something like below:

fileChangedHandler = (event) => {
    let file_size = event.target.files[0].size;

    //or if you like to have name and type
    let file_name = event.target.files[0].name;
    let file_type = event.target.files[0].type;
   //do whatever operation you want to do here
};

Upvotes: 16

a.developer
a.developer

Reputation: 49

You will first need to grab the input type file upload like var uploadDocuments = document.getElementById('file-0'); //grab html file-upload element

and can get the file size using .size attribute.

uploadDocuments.files[0].size //this gives the size of uploaded file

Upvotes: 1

Cyrus
Cyrus

Reputation: 47

React.js is just used for your view. You can use normal javascript for everything else.

If you wanted to find a file's size at some url with jquery:

var req = $.ajax({
  type: "HEAD",
  url: 'some/url/here',
  success: function () {
    console.log(req.getResponseHeader("Content-Length")); //Filesize
  }
});

In the success callback you could save the size into React's state using setState(), then display the size in a div within your render method.

You are also not limited to using jquery for the HEAD request. SuperAgent is another popular one.

Upvotes: -1

Related Questions