Attempting to prepare a file with fs to upload to a server via php

70 Views Asked by At

I currently have a local file path

var localFile = "/Desktop/here/myfile.jpg";

  const buffer = fs.readFileSync(localFile);
  const fileName = 'thumb.jpg';

I then attempt to add this to a FormData object like so:

  formData.append('file', buffer, {
    contentType: 'text/plain',
    name: 'file',
    filename: fileName,
  });

I then get the error:

Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'.

I'm a little confused on the fs stream. Shouldn't the readFileSync create the blob?

1

There are 1 best solutions below

0
FabricioG On

I ended up doing it like this:

  fs.readFile(`${localFile}`, (error, data) => {
    if(error) {
        throw error;
    }
      formData.append('file', data);

});