Wanted pass file in body form-data using scripting

Hey folks,
I have data in a table through which I have already created a CSV file using scripting and now I want to pass that file in the Body form-data of an API but don't want to download the file and upload it. Preferably, looking for a JS way to do it.

Thanks in advance, Cheers!!

Hi @Tanmaysriv, welcome to the community! :wave:

You can pass the data (the one you pass before you convert into csv) as a base64 value to whatever body you want to pass it on.

I did something similar to sending an email with an excel file attachment. I did something like:

const aTable = XLSX.utils.json_to_sheet(o.active);
const iTable = XLSX.utils.json_to_sheet(o.inactive);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, aTable, "Sheet Title: active")
XLSX.utils.book_append_sheet(workbook, iTable, "Sheet Title: inactive")
const result = XLSX.write(workbook, {type: "base64"})

I pass the result to the gmail api endpoint for sending emails with attachment.

Hey @jocen,
Thanks for the solution. Could you please help me with the process of importing XLSX library in the script?

Hey @Tanmaysriv, that's only a sample of using base64 encode to pass data. Do you need to pass the data as an excel file or not? if not, then you don't have to import XLSX library. You can simply follow the implementation of this base64 converter from Retool Utilities.

If you need to pass it on as an excel file, then you can follow this thread for the implementation. aturiot gave instructions on how to add the library to your app.

Hey @jocen, I've to pass csv file in Post request my script and query looks like this:

Is this correct? Because, I'm getting 400 from API.

So, found the issue. Here we've to send metadata of the file from our end as mentioned below:

const requestCsvData = {
    name: "request.csv",
    size: csvFile.length,
    lastModified: moment().unix(),
    type: "text/csv",
    data: csvFile, //this is in base64
}

const apiResponse = await cloudwaysRetry.trigger({
            additionalScope: {
                csvFile: requestCsvData,
            },
        });