Search code examples
reactjsinputsocket.io

How do I get the actual file from an Input type file element?


var file = e.target.files[0];

or

var file = e.target.value;

I'm using React and socket.io to try to sent images over chat. All I've been able to get is the file path not the actual file. I've never handled file inputs so I'm trying to figure out how to take that file and convert it to a binary string I can send over socket.io.

help? any packages you would recommend?


Solution

  • You need to get file from input for example you can fire handler on onChange event. After this you must put your file from input(e.target.file[0] or loop if files many) to FileReader and extract blob from file. Next you can send extracted blob through socket, if blob is too large you can slice it to chunks.

    There is example of code:

    const readBlob = file => new Promise((resolve, reject) => {
      const reader = new FileReader();
    
      reader.onload = e => {
        resolve(e.target.result);
      };
    
      reader.readAsText(file);
    });
    

    Sorry for my English!)