424

I am using Spring MVC and this is my method:

/**
* Upload single file using Spring Controller.
*/
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public @ResponseBody ResponseEntity<GenericResponseVO<? extends IServiceVO>> uploadFileHandler(
            @RequestParam("name") String name,
            @RequestParam("file") MultipartFile file,
            HttpServletRequest request,
            HttpServletResponse response) {

    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            String rootPath = System.getProperty("catalina.home");
            File dir = new File(rootPath + File.separator + "tmpFiles");
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();

            System.out.println("Server File Location=" + serverFile.getAbsolutePath());

            return null;
        } catch (Exception e) {
            return null;
        }
    }
}


I need to pass the session id in postman and also the file. How can I do that?

informatik01
  • 16,038
  • 10
  • 74
  • 104
Harikrishnan K.N.
  • 4,560
  • 2
  • 17
  • 28
  • 2
    AFTER ALL IS SAID AND DONE this fixed my issue add `[]` to the name of the file upload parameter eg. `image[]` `file[]` `upload[]` – Ray Zion Aug 11 '20 at 11:15
  • Here is a quick 2 minute video tutorial https://youtu.be/sFlPa_Vow3w – VedantK Aug 22 '21 at 11:48

24 Answers24

799

In postman, set method type to POST.

Then select Body -> form-data -> Enter your parameter name (file according to your code)

On the right side of the Key field, while hovering your mouse over it, there is a dropdown menu to select between Text/File. Select File, then a "Select Files" button will appear in the Value field.

For rest of "text" based parameters, you can post it like normally you do with postman. Just enter parameter name and select "text" from that right side dropdown menu and enter any value for it, hit send button. Your controller method should get called.

Greg T
  • 3,278
  • 3
  • 37
  • 39
jarvo69
  • 7,908
  • 2
  • 18
  • 28
  • 22
    Why `POST`? What about `PUT`? – Green Sep 06 '17 at 12:03
  • 4
    What do you mean by "Doesnt work"? Why dont you show your code for us to debug issue easily? – jarvo69 Sep 07 '17 at 04:16
  • 2
    I get the text part as `String` always. Why does it not map to my DTO? `@PostMapping ( value = "/byImageFile", consumes = { "multipart/form-data" }) public ResponseEntity> postMap( @RequestPart ( "imageFile") MultipartFile imageFile, @RequestPart ( "fieldsToExtract") RequestDto requestDto )` Iam not able to send the requesst from postman at all in this case – Arun Gowda Sep 03 '18 at 11:10
  • @ArunGowda Try posting your query as new Question. As it is different from the question poster here and answer given is relevant to question posted here by OP. – jarvo69 Sep 04 '18 at 04:50
  • 4
    I found my solution. It won't map to `RequestDto`automatically. I took it as a string, parsed the `Json` and mapped it to `RequestDto` explicitly. – Arun Gowda Sep 04 '18 at 13:22
  • 3
    I want to send the file along with the json data not with the form-data, is there any way possible to do it ? – rammanoj Dec 14 '18 at 05:22
  • @SumitBadaya can i send file using raw option with other paramters in json form? – Romil Patel Mar 05 '19 at 09:58
  • 1
    @Green Checkout Kubilay's answer regarding `PUT`. https://stackoverflow.com/a/50675894/7376590 – steven7mwesigwa Aug 23 '20 at 09:36
  • 5
    This is partly correct. You must also set the content type for each json field to application/json. You can do this by clicking the ellipsis next to the 'Bulk edit' link inside Postman. – Chris Aug 25 '20 at 21:55
  • Can you please tell me how to implement get() with postman to receive file response – Muhammad Usama Rabani Sep 01 '20 at 10:05
362

The Missing Visual Guide

You must first find the nearly-invisible pale-grey-on-white dropdown for File which is the magic key that unlocks the Choose Files button.

After you choose POST, then choose Body->form-data, then find the File dropdown, and then choose 'File', only then will the 'Choose Files' button magically appear:

Postman POST file setup - (Text,File) dropdown highlighted

Chris F Carroll
  • 11,146
  • 3
  • 53
  • 61
  • 26
    you are correct in that the UI for this is invisible to the non-initiated. Thank you for the visual version! – Vijay Nov 16 '19 at 22:34
  • 1
    what if I have an XML body payload and the attachment? – tuxErrante Mar 23 '20 at 17:10
  • gce's answer seems to say you can do it easily enought? I'm not sure . You might have to learn how to combine the attachment and the XML into a single document by learning about the multi-part mime format. Which isn't too complicated, you can create a multipart mime body by hand. – Chris F Carroll Mar 24 '20 at 23:17
  • 12
    Two years later, the UI has not been improved any. – Sabuncu May 18 '20 at 13:19
  • Can you please tell me how to implement get() with postman to receive file response? – Muhammad Usama Rabani Sep 01 '20 at 10:05
  • Ah. Perhaps another picture is need. Depending on how your postman window is laid out, the response should simply appear underneath where you send the request. It displays html and images but for other files there is a save button? – Chris F Carroll Sep 01 '20 at 14:27
  • Brother. You are the boss – Mese Oct 18 '21 at 09:52
  • 2
    Late 2021 update about the UI and the nearly invisible drowdown: you can only see that dropdown if **none** of the text inputs of **that line** currently holds the cursor. So move away with tab key to make it appear... – Fabien Haddadi Dec 16 '21 at 20:30
  • I would have never found that nearly invisible dropdown. What an odd design choice. Thank you for the heads up! – jyoseph Apr 19 '22 at 20:46
  • And @tuxErrante I came here looking for that answer. I believe you do the above instructions to send a file and then select the 'raw' radio button to the right. You'll then get a dropdown for format to choose - 'XML' and throw your XML in there. Not sure if that will work though - I'm going to test soon. – fIwJlxSzApHEZIl Jan 12 '23 at 14:30
  • it's almost 2024 and still the UI has not been improved for the dropdown select – Anas Aug 05 '23 at 09:18
86

Maybe you could do it this way:

postman_file_upload_with_json

gce
  • 1,563
  • 15
  • 17
37

Like this :

enter image description here

Body -> form-data -> select file

You must write "file" instead of "name"

Also you can send JSON data from Body -> raw field. (Just paste JSON string)

enter image description here

burakozgul
  • 775
  • 6
  • 11
36

enter image description here

I got confused after seeing all of the answers, I couldn't find any proper screenshot to bring the Content Type column. After some time, I found it by my own. Hope this will help somebody like me.

Here is the steps:

  1. click on red marked area of postman.
  2. Now check the green marked option (Content Type).
  3. Now change the search content type, in the yellow marked area.

In my case:

  1. invoice_id_ls (key) contains the json data.
  2. documents contains the file data.
  3. placed_amount contains normal text string.
Farid Chowdhury
  • 2,766
  • 1
  • 26
  • 21
  • How does the filename relate to the file to be included in the JSON attached? – Jam Jun 09 '21 at 10:34
  • 1
    Yes, this is the missing part of this quest. Spring doesn't want to treat json text as json until its content-type is set manually. – Sneg Nov 05 '21 at 21:09
  • This solution worked for me, the clearest answer in this post. Normally my request body has several fields, so had to set several key-value paris as `application/json` in the `CONTENT_TYPE` column. Leaving the file as `auto` in that same column. – Seb Jan 14 '22 at 08:09
  • This is the correct answer for sending files + a json text filed in the form-data post request. Thank you so much!!! – myforums Jan 26 '22 at 19:42
19

Postman multipart form-data content-type

Select [Content Type] from [SHOW COLUMNS] then set content-type of "application/json" to the parameter of json text.

otamega
  • 229
  • 2
  • 5
18
  1. Don't give any headers.
  2. Put your json data inside a .json file.
  3. Select your both files one is your .txt file and other is .json file for your request param keys.
Rohit Thakur
  • 244
  • 2
  • 12
  • This is a good answer.. This can also be used for use cases where multiple file has to be uploaded along with a json payload in a multi-part payload.. – Kiran Apr 11 '18 at 19:57
  • 1
    This is the most correct answer if you want to send a File as well as JSON data. Examples showing selecting a file and then the JSON data being passed as a single JSON string value or splitting the values up do not work (possibly depending on the end point but I can't verify this). It is also mentioned here: https://github.com/postmanlabs/postman-app-support/issues/3331 – Anto Jul 17 '18 at 10:59
18

If somebody wants to send json data in form-data format just need to declare the variables like this

Postman:

As you see, the description parameter will be in basic json format, result of that:

{ description: { spanish: 'hola', english: 'hello' } }
miselking
  • 3,043
  • 4
  • 28
  • 39
14

Kindly follow steps from top to bottom as shown in below image.

postman image

At third step you will find dropdown of type selection as shown in below image

postman dropdown

Ankur prajapati
  • 485
  • 6
  • 9
  • could u please help explain or point me to a resource on how to work with these API keys for authenticating apis ? I am using laravel admin for some project and its base code is rather confusing on how to use libraries like passport to generate API tokens. many thanks – NMukama Jun 13 '22 at 13:31
  • you can pass through the Authorization tab of postman. In that Select Type: API Key and after that pass value in the key & value textbox. Once you are done with after this if you pass a parameter through the body it will automatically get authenticated. – Ankur prajapati Jun 23 '22 at 13:56
13

Body > binary > Select File

enter image description here

code-8
  • 54,650
  • 106
  • 352
  • 604
11

If you need like Upload file in multipart using form data and send json data(Dto object) in same POST Request

Get yor JSON object as String in Controller and make it Deserialize by adding this line

ContactDto contactDto  = new ObjectMapper().readValue(yourJSONString, ContactDto.class);
EstevaoLuis
  • 2,422
  • 7
  • 33
  • 40
Ajay k
  • 121
  • 1
  • 5
  • 1
    Can you tell me what are the two headers used? – Abhisek Roy Apr 10 '19 at 05:52
  • Content-Type : application/json Authorization : bearer (yourTokenString) – Ajay k May 14 '19 at 07:40
  • 1
    Yes it worked. Thanks. I used below code and worked : @PostMapping(value = Constant.API_INITIAL + "/uploadFile") public UploadFileResponse uploadFile(@RequestParam("file") MultipartFile file,String jsonFileVo) { FileUploadVo fileUploadVo = null; try { fileUploadVo = new ObjectMapper().readValue(jsonFileVo, FileUploadVo.class); } catch (Exception e) { e.printStackTrace(); } – Anand_5050 Dec 22 '19 at 17:10
  • you can set the Content-Type for contactDtoString to application/json, you can do this for every key – Hritcu Andrei Mar 25 '20 at 16:05
9

If somebody needed:

body -> form-data

Add field name as array

enter image description here

Marcos Dantas
  • 836
  • 1
  • 11
  • 10
6

Use below code in spring rest side :

@PostMapping(value = Constant.API_INITIAL + "/uploadFile")
    public UploadFileResponse uploadFile(@RequestParam("file") MultipartFile file,String jsonFileVo) {
        FileUploadVo fileUploadVo = null;
        try {
            fileUploadVo = new ObjectMapper().readValue(jsonFileVo, FileUploadVo.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

enter image description here

Anand_5050
  • 1,019
  • 2
  • 10
  • 23
5

If you want to make a PUT request, just do everything as a POST request but add _method => PUT to your form-data parameters.

kubilay
  • 5,047
  • 7
  • 48
  • 66
5

The way to send mulitpart data which containts a file with the json data is the following, we need to set the content-type of the respective json key fields to 'application/json' in the postman body tab like the following: enter image description here

Ahsan Farooq
  • 819
  • 9
  • 10
5

You can send both Image and optional/mandatory parameters.

In postman, there is Params tab.

Kai-Sheng Yang
  • 1,535
  • 4
  • 15
  • 21
4

I needed to pass both: a file and an integer. I did it this way:

  1. needed to pass a file to upload: did it as per Sumit's answer.

    Request type : POST

    Body -> form-data

    under the heading KEY, entered the name of the variable ('file' in my backend code).

    in the backend:

    file = request.files['file']

    Next to 'file', there's a drop-down box which allows you to choose between 'File' or 'Text'. Chose 'File' and under the heading VALUE, 'Select files' appeared. Clicked on this which opened a window to select the file.

2. needed to pass an integer:

went to:

Params

entered variable name (e.g.: id) under KEY and its value (e.g.: 1) under VALUE

in the backend:

id = request.args.get('id')

Worked!

vinci mojamdar
  • 614
  • 5
  • 6
2

For each form data key you can set Content-Type, there is a postman button on the right to add the Content-Type column, and you don't have to parse a json from a string inside your Controller.

Hritcu Andrei
  • 172
  • 10
2

first, set post in method and fill link API

Then select Body -> form-data -> Enter your parameter name (file according to your code)

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 22 '21 at 13:37
0

If you are using cookies to keep session, you can use interceptor to share cookies from browser to postman.

Also to upload a file you can use form-data tab under body tab on postman, In which you can provide data in key-value format and for each key you can select the type of value text/file. when you select file type option appeared to upload the file.

Sandesh Jain
  • 704
  • 3
  • 13
0

If you want the Id and File in one object you can add your request object to a method as standard and then within Postman set the Body to form-data and prefix your keys with your request object name. e.g. request.SessionId and request.File.

Tom McDonough
  • 1,176
  • 15
  • 18
0

The steps of uploading a file through postman along with passing some input data is very well discussed in below blog along with the screenshot. In this blog, the api code is written in node js. You can go through it once to have more clarity.

https://jksnu.blogspot.com/2021/09/how-to-create-post-request-with.html

-2

At Back-end part

Rest service in Controller will have mixed @RequestPart and MultipartFile to serve such Multipart + JSON request.

@RequestMapping(value = "/executesampleservice", method = RequestMethod.POST,
consumes = {"multipart/form-data"})

@ResponseBody
public boolean yourEndpointMethod(
    @RequestPart("properties") @Valid ConnectionProperties properties,
    @RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
return projectService.executeSampleService(properties, file);
}

At front-end :

formData = new FormData();

formData.append("file", document.forms[formName].file.files[0]);
formData.append('properties', new Blob([JSON.stringify({
            "name": "root",
            "password": "root"                    
        })], {
            type: "application/json"
        }));

See in the image (POSTMAN request):

Click to view Postman request in form data for both file and json

-2

To send image along with json data in postman you just have to follow the below steps .

  • Make your method to post in postman
  • go to the body section and click on form-data
  • provide your field name select file from the dropdown list as shown below
  • you can also provide your other fields .
  • now just write your image storing code in your controller as shown below .

postman : enter image description here

my controller :

public function sendImage(Request $request)
{
    $image=new ImgUpload;  
    if($request->hasfile('image'))  
    {  
        $file=$request->file('image');  
        $extension=$file->getClientOriginalExtension();  
        $filename=time().'.'.$extension;  
        $file->move('public/upload/userimg/',$filename);  
        $image->image=$filename;  
    }  
    else  
    {  
        return $request;  
        $image->image='';  
    }  
    $image->save();
    return response()->json(['response'=>['code'=>'200','message'=>'image uploaded successfull']]);
}

That's it hope it will help you

kishan maharana
  • 623
  • 8
  • 10