How to add file in a pre-request script using form data

I am trying to create a request in the pre-request script using in the form-data and in the body i would like to upload a pdf file from my working directory.

I used the following script and i dont know why it not uploading the file.
Can you please help ?

        "body":{ 
            "mode": "formdata",
            "formdata": [
                 { "key" : "file","value": "X:\\Postman\\files\\test.pdf", "disabled" : false, "description" : {"content" :"", "type" :"file"}},
                { "key" : "text","value": "text", "disabled" : false, "description" : {"content" :"", "type" :"text"}},
                { "key" : "Number","value": "12345686", "disabled" : false, "description" : {"content" :"", "type" :"text"}},
                { "key" : "Text","value": "0011002327", "disabled" : false, "description" : {"content" :"", "type" :"text"}},  
                { "key" : "Date","value": "02/12/2020", "disabled" : false, "description" : {"content" :"", "type" :"text"}}
   ]}  

Your question may already have an answer on the community forum. Please search for related topics, and then read through the guidelines before creating a new topic.

Hi @a_frixou,

Welcome to the Postman community! :clap:

This is a great question, that sadly has no easy answer.

To start, the node js sandbox in Postman (pre-request or test script sections), do not support reading from the file system. In order for you to create a formdata request, the sandbox would have to read the file from the file system, with the given path. Sadly, just leaving it as text willnot suffice.

However, there may be a manual way you can do this. If you’re consistently using the same file, you can get the base64 encoded version of the file, and use that in the upload, as opposed to the file location as you have done. I am not 100% certain this will work, as from my research, it looks like the file is first opened in a binary format, when doing any mulitpart/formdata request, and then its base64 encoded before being sent over. Chances are you can do this, but I have not tried it.

I would make a base64 string of the “test.pdf” file, then put that as the value for the key “file” instead of the file location, and see if that works.

Hope this helps!
Orest