Crea
Crea

Reputation: 47

reactJS windows.FileReader readAsArrayBuffer method error

Error in reactJS using drop-zone to receive files and replace them with byte buffers

TypeError: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.

  onDrop = async (file) => {
try {     
  console.log(file.name);
  let reader = new window.FileReader();
  reader.readAsArrayBuffer(file); // <<== Error occurred here
  const buffer = await Buffer.from(reader.result);
  console.log(buffer.length);
} catch (error) {
  console.log(error);
}

how can i fix this .. please help

Upvotes: 1

Views: 917

Answers (1)

Mos&#232; Raguzzini
Mos&#232; Raguzzini

Reputation: 15851

Hi mate there was several issues in your code, checkout:

  • How I retrieved the file: the function argument (this) refers to the input that called the method, not the file
  • the FileReader API only supports callbacks if you want use async/await you have to wrap it in your own method promise-managed
  • To know the buffer length you have to call ArrayBuffer.byteLength
  • additionally, if you are not using any libraries and you are working outside a NODE env, Buffer will be undefined

function readFileAsync(file) {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();

    reader.onload = () => {
      resolve(reader.result);
    };

    reader.onerror = reject;

    reader.readAsArrayBuffer(file);
  })
}

const readURL = async (input) => {
  try {
    const file = input.files[0]; // this is where your file data is
    console.log(file.name);
    let contentBuffer = await readFileAsync(file);
    console.log(contentBuffer.byteLength); // Length in ArrayBuffer
  } catch (error) {
    console.log(error);
  }
}
<input type='file' id="upload" onchange="readURL(this)" />

Upvotes: 1

Related Questions