Request Body Update

Hi ,
I have scenario where I have some files converted to BAse64 format and I need to paste content in Request Body (Raw /Text) or Raw/JSON . These are huge in content.

Is there a way to do this via prerequisite script like passing file name or something. looking for passing file name as downthe line would like to parametrize this collection

Yes, there is a way to include the content of a file in the request body of a Postman request using a pre-request script. Here is an example of how you can do this using JavaScript:

1. In your Postman request, select "Pre-request Script" from the "Tests" tab.
2. In the script editor, you can use the JavaScript `fs` (file system) module to read the file and get its content. For example, you can use the following code to read the file:



Preformatted textconst fs = require(‘fs’);
const fileName = ‘path/to/file.txt’;
const fileContent = fs.readFileSync(fileName, ‘utf8’);


3. To pass the content of the file as the request body, you can set the `pm.environment.set` method and set the value of the `fileContent` variable.

pm.environment.set(“fileContent”, fileContent);


4. In the request body select the "raw" and "text" option and type `{{fileContent}}`
5. You can parametrize this collection by using environment variables in the file path, so that you can change the file name dynamically at runtime.

const fileName = path/to/${pm.environment.get("fileName")};


It's worth noting that this code assumes that the file is located on the same machine as the Postman application. If the file is located on a remote server, you will need to use a different approach to read the file, such as using the `http` module to make a request to the file's URL.

@payload-pilot-965338

I can’t see the filesystem (fs) external library in the Postman JavaScript reference.

Postman JavaScript reference | Using external libraries

If I try and run this, I get “fs.readFileSync is not a function”.

Tried some of the other fs functions with similar results.

If I console.log(fs), I get an empty object instead of a function that you would normally get.

Do you have screenshots of this working?

Only asking as having the fs library available would be useful to have in the toolbox.

I am facing the same issue. Please let me know if you find anything

@rb12121

It’s not currently part of the sandbox, and I don’t think there are any plans for it to be.

However, you can use the Newman node.js libraries in conjunction with the filesystem libraries, but it means you need to know about about node and a decent level of JavaScript.

Here are some links and examples.

newman - npm (npmjs.com)

[Feature] possibility to programatically write to a file ¡ Issue #3033 ¡ postmanlabs/postman-app-support ¡ GitHub

1 Like