Javascript transform <input> file to binary

Viewed 26

I am trying to transform the file from the input element to raw binary data and then upload it to the server with the help of axios.put

The main/problematic parts of the code in my opinion are:

  const file = document.getElementById('file').files[0]

  async function getBinaryFromFile(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.addEventListener('load', () => resolve(reader.result))
      reader.addEventListener('error', (err) => reject(err))
      reader.readAsBinaryString(file)
    })
  }

  const binary = await getBinaryFromFile(file)

  const config = {
      data: binary,
      signal: controller.value.signal
   }

  axios.put(`${url}/${uuid}/file/${file.name}`, binary, config)

This is the output if I console.log(binary):

-----------------------------220913591021183570121419664829

Content-Disposition: form-data; name="data"; filename="Additional-1.pdf"

Content-Type: application/pdf

%PDF-1.5 %���� 4 0 obj /Length 5 0 R /Filter /FlateDecode

stream x��}[�f7r�����S�z���; ��r1�8�����a������#;�{2�?\kU��N�zz$��Nշ77Y����dx��a�'����w}�~���u��;�1����_=�������ӷ�x�e���[ZP�/)�������{��o�������#<������o�{���_������w칔���u?�r������7����W��?{��#�Q��|�_rK����1������%�q'�w��C��8^�(�cx���R�\�ܝ��;����s���/c��|ꉈ~�����k��1��p �|虈��@��Bj�*/�7{x�a��Dž��&��8���p"����b��(�nV�c��>�۰���Qo��� ��|�U���J�CԻ�勤��E���O֙:����ϳ� �Z��^���t�����������S�SQC�_�����~��&9C����.+/#tc����*pr��S���M�=g�\�vH���= |�!�����K�q��&!��$��yL��OG��zW��[to�Ik����p����mb0� ��H!+������ RB��[�`~�\�<1ar�dQ�'���D(�DLEB�^������~\��=��a�u,��Ĺ� ��������'�J���>����Q>e����[�................

If I download the file from the server afterwards I get an error that it cannot be displayed or a blank PDF. What am I doing wrong here? Why do I get this gibberish?

2 Answers

I don't think you are getting gibberish. Remember, a "binary string" is a string containing values that may not have glyphs associated with them in a font.

That said, readAsBinaryString isn't how I would do this in new code (and in any case, there's no reason to supply the data both as an argument and in the config.data property). File objects are Blobs, and axios can handle accepting a blob as data:

const file = document.getElementById("file").files[0];

const binary = await getBinaryFromFile(file);

const config = {
    data: file, // ***
    signal: controller.value.signal,
};

axios.put(`${url}/${uuid}/file/${file.name}`, config);

The solution was quite easy instead of using reader.readAsBinaryString(file) I used reader.readAsArrayBuffer(file) and it works like a charm.

Related