APIs & Integrations

TaylorAran
Member

Error 415 when uploading files

Hello,

 

When trying to upload a PDF file via fetch(), I keep getting a 415 error. The PDF file is saved in the same directory as the js file.

 

Please see my function. I have tried changing the "Content-Type" in headers to several different options, and all spit back 400 and 415 errors.

 

When I use request.post() instead of fetch(), I can upload the file. But I want to use fetch(). So what's the issue?

 

Any help you can provide would be much appreciated.

 

 

 

async function uploadFile(filePath, extension, timestamp) {

    const url = "https://api.hubapi.com/files/v3/files";
    var filename = `${filePath}.${extension}`;

    var fileOptions = {
        access: 'PRIVATE',
        overwrite: false,
        duplicateValidationStrategy: 'NONE',
        duplicateValidationScope: 'ENTIRE_PORTAL'
    };

    var formData = {
        file: fs.createReadStream(filename),
        fileName: `${filename} (${timestamp}).${extension}`,
        options: JSON.stringify(fileOptions),
        folderPath: 'Quotations'
    };

    try {
        const response = await fetch(url, { 
            "method": "POST",
            "formData": formData,
            "headers": {
                'Authorization': `Bearer ${process.env.ACCESS_TOKEN}`,
                "Content-Type": "application/pdf"
            }
        });

        if(!response.ok) {
            throw new Error(`HTTP Error: ${response.status}`);
        }
        
        const data = await response.json();
        return data;

    } catch(error) {
        console.log(`Error: ${error}`);
    }

}

const fileId = uploadFile("Quotation", "pdf", getCurrentTimestamp());
fileId.then((data) => console.log(data));

 

 

 

0 Upvotes
3 Replies 3
JairoPy
Member

Error 415 when uploading files

Have you tried setting the content type as multipart/form-data?

0 Upvotes
TaylorAran
Member

Error 415 when uploading files

Hi @JairoPy,

 

Thanks for your reply.

 

Yes, I have tried that, but the reponse is always: "Error: Error: HTTP Error: 400".

I have also tried "application/json", which returns: "Error: Error: HTTP Error: 415". 

Commenting out the "Content-Type" line returns: "Error: Error: HTTP Error: 400".

 

For the sake of trying everything, I also tried "text/plain", but that returns "Error: Error: HTTP Error: 415". 

0 Upvotes
JairoPy
Member

Error 415 when uploading files

Well, I guess the issue is that the fetch api as it is client side is subject to cross origin problems, as this endpoint requests authorization you just be able to reach it from your backend, that's why you're request works with the request node package but no with fetch api.

 

If you want to fetch any info from this api to the frontend, you could create an internal api to gather the data from hubspot and expose it to your client side.