1

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

1 Answer 1

1

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)" />

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.