I cannot get file name of a file uploaded in form-data request body:
I tried: pm.request.body
, it returns the request body:
{mode: "formdata", formdata: [1]}
mode: "formdata"
formdata: [1]
0: {…}
key: "file"
type: "file"
src: "/Users/errorfile.csv"
but when I tried pm.request.body.formdata.src
, it returns undefined.
When I tried pm.request.body.formdata[0].src
, it shows error:
"TypeError: Cannot read properties of undefined (reading 'src')"
The pm.request.body.formdata
is data object.
So you need to convert JSON object.
Pre-request Script
const jsonData = JSON.parse(JSON.stringify(pm.request.body.formdata));
console.log(jsonData[0]);
console.log(jsonData[0].key);
console.log(jsonData[0].type);
console.log(jsonData[0].src);
console output
{key: "csvFile", type: "file", src: "/D:/temp/errFile.csv"}
csvFile
file
/D:/temp/errFile.csv
The JSON.parse(JSON.stringify()) technique is used to create a deep copy of an object in JavaScript.
The JSON.stringify() function converts JavaScript objects into JSON strings
JSON.parse() - This converts the JSON string back into a JavaScript object.
Once you have a deep copy of the form data, you can access its properties like any other JavaScript object.