Trying to upload PDF file- node.js

I am trying to upload PDF file using Files API endpoint, with the below code I can upload the file, but the “File Preview” shows “Failed to load PDF document”. I need help. Here’s the code

const axios= require(‘axios’);

const fs = require(‘node:fs’);

let buf;

async function readPdfFile(){

fs. readFile("xyz.pdf", (err,data) =>{

    if(err){

      console.error(err);

      return;

    } buf= (Buffer.from(data).toString('base64'));

  });

  const file\_blob = new Blob(\[buf], {

          type: "application/pdf",

        });

          const folderId= 'hsFolderID';

          const form\_data= new FormData();

          form\_data.append("file", file\_blob, "random3.pdf");

          form\_data.append("folderId", folderId);

          form\_data.append(

          "options",

          JSON.stringify({

          access: "PRIVATE",

          overwrite: true,

          duplicateValidationStrategy: "NONE",

          duplicateValidationScope: "EXACT\_FOLDER",

          }))

          const request\_config= {

          headers:{

              "Authorization": "Bearer " + "\*\*\*\*\*\*\*\*\*\*\*",

              "Content-Type": "multipart/form-data"

          },

          data: form\_data

          };

          const url= 'https://api.hubapi.com/files/v3/files'

          return axios.post(url, form\_data, request\_config);

}

readPdfFile()

FYI- The input file is provided by our another system and the pdf file produced by this system looks like this

{
fileName: ‘Abc.pdf’,
buffer: <Buffer 24 57 45 83 89 2e 43 0a 32 21 67 34 6f 63 6a 0a 4c 3c 0a 2f 65 32 46 6c … 51377 more bytes>
}. Using this as input I have to upload it to hubspot and view the pdf file in hubspot

Hey, @AngelKanna :waving_hand: I hope you got this worked out. If no, have you tried a simplified test by using Postman?

I just did this and was successful in viewing my uploaded PDF.

Steps:

  • File preview

  • This is the Node example using Axios that Postman provided

    const axios = require('axios');
    const FormData = require('form-data');
    const fs = require('fs');
    let data = new FormData();
    data.append('file', fs.createReadStream('3BYwspxB8/Hello.pdf'));
    data.append('folderId', '92105487368');
    data.append('options', '{"access":"PRIVATE"}');
    
    let config = {
     method: 'post',
     maxBodyLength: Infinity,
     url: 'https://api.hubapi.com/files/v3/files/',
     headers: { 
     'Authorization': 'Bearer NOPE', 
     'Cookie': 'a_long_string', 
     ...data.getHeaders()
     },
     data : data
    };
    
    axios.request(config)
    .then((response) => {
     console.log(JSON.stringify(response.data));
    })
    .catch((error) => {
     console.log(error);
    });
    ​
    

I hope this helps get you moving forward! — Jaycee

Thank you Jaycee_Lewis, it worked

The above code works for a single file upload, but if I have an array of file paths

filePaths = [‘abc.pdf’, ‘sample.pdf’,‘xyz.pdf’] all files are in current directory. When I loop over the array, the code just uploads the last file 3 times to hubspot folder. I think fs.createReadStream() should be async. please advise

const axios = require(‘axios’);

const FormData = require(‘form-data’);

const fs = require(‘fs’);

let data = new FormData();

const filePaths = [‘abc.pdf’, ‘sample.pdf’,‘xyz.pdf’];

async function toCall(){

for(var i=0; i< filePaths.length; i++){

await getFormData(filePaths[i]);

let config = {

method: ‘post’,

maxBodyLength: Infinity,

url: ‘https://api.hubapi.com/files/v3/files/’,

headers: {

'Authorization': 'Bearer \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*',

...data.getHeaders()

},

data : data

};

axios.request(config)

.then((response) => {

console.log(JSON.stringify(response.data));

})

.catch((error) => {

console.log(error);

});

}

}

async function getFormData(path)

{

data.append('file', fs.createReadStream(path));

data.append('folderId', '\*\*\*\*\*\*\*\*\*\*');

data.append('options', '{"access":"PRIVATE"}');

}

toCall();