-1

I'm trying to create a postman prerequisite script to upload a file to our API using a form data

My body is given below. Now, the problem is that if put my base64 string in the value field where the key is "file" our API still returns an error where "Field file is required". Is it right that I should just insert the base64 string there?

 body: {
    "mode": "formdata",
    "formdata" : [
       {"key":"file", "value":"insert base64 string here"},
       {"key":"dc", "value": 'someValue' }
       
    ]
}
MagsTester
  • 35
  • 1
  • 1
  • 3

1 Answers1

0

Here is the code that should work for sending a file as a base64 string in a form-data request using Postman:

const fs = require('fs');
const path = require('path');

const filePath = 'path_to_your_file'; // Replace with the actual path to your file
const base64Data = fs.readFileSync(filePath, { encoding: 'base64' });

const requestBody = {
    mode: 'formdata',
    formdata: [
        { key: 'file', value: base64Data },
        { key: 'dc', value: 'someValue' }
    ]
};

pm.request.body.update(requestBody);

Make sure you replace 'path_to_your_file' with the actual path to the file you want to upload. This script reads the file, encodes it as a base64 string, and then includes it in the formdata section of the request body along with the "dc" key.

Note that directly inserting the base64 string into the "value" field in your original script might not work as expected, as some APIs might require specific formatting or encoding for file uploads. Using the approach described above ensures that the file is encoded correctly before being included in the form data.

  • Hi kaylei, thanks for your reply. I tried your suggestion but i'm having troubles. I encountered "TypeError: fs.readFileSync is not a function" it seems postman does not support 'fs' – MagsTester Aug 27 '23 at 13:29