How to upload a file and JSON data in Postman?

JavaJsonSpring MvcPostman

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

In postman, set method type to POST.

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

and on right side next to value column, there will be dropdown "text, file", select File. choose your image file and post it.

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.

Solution 2 - Java

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

Solution 3 - Java

Maybe you could do it this way:

postman_file_upload_with_json

Solution 4 - Java

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

Solution 5 - Java

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.

Solution 6 - Java

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.

Solution 7 - Java

  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.

Solution 8 - Java

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

Postman:

https://i.stack.imgur.com/e6d3Q.png" />

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

{ description: { spanish: 'hola', english: 'hello' } }

Solution 9 - Java

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

Solution 10 - Java

Body > binary > Select File

enter image description here

Solution 11 - Java

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);

Solution 12 - Java

If somebody needed:

body -> form-data

Add field name as array

enter image description here

Solution 13 - Java

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

Solution 14 - Java

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

Solution 15 - Java

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.

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!

Solution 16 - Java

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

Solution 17 - Java

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.

Solution 18 - Java

first, set post in method and fill link API

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

Solution 19 - Java

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.

Solution 20 - Java

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.

Solution 21 - Java

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

Solution 22 - Java

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

Solution 23 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHarikrishnan K.N.View Question on Stackoverflow
Solution 1 - Javajarvo69View Answer on Stackoverflow
Solution 2 - JavaChris F CarrollView Answer on Stackoverflow
Solution 3 - JavagceView Answer on Stackoverflow
Solution 4 - JavaburakozgulView Answer on Stackoverflow
Solution 5 - JavaFarid ChowdhuryView Answer on Stackoverflow
Solution 6 - JavaotamegaView Answer on Stackoverflow
Solution 7 - JavaRohit ThakurView Answer on Stackoverflow
Solution 8 - JavaSebastian ArdilaView Answer on Stackoverflow
Solution 9 - JavaAnkur prajapatiView Answer on Stackoverflow
Solution 10 - Javacode-8View Answer on Stackoverflow
Solution 11 - JavaAjay kView Answer on Stackoverflow
Solution 12 - JavaMarcos DantasView Answer on Stackoverflow
Solution 13 - JavaAnand_5050View Answer on Stackoverflow
Solution 14 - JavakubilayView Answer on Stackoverflow
Solution 15 - Javavinci mojamdarView Answer on Stackoverflow
Solution 16 - JavaAhsan FarooqView Answer on Stackoverflow
Solution 17 - JavaHritcu AndreiView Answer on Stackoverflow
Solution 18 - JavaRizka KhoirotunnisaView Answer on Stackoverflow
Solution 19 - JavaSandesh JainView Answer on Stackoverflow
Solution 20 - JavaTom McDonoughView Answer on Stackoverflow
Solution 21 - Javajitendra singhView Answer on Stackoverflow
Solution 22 - JavaAnshu KumarView Answer on Stackoverflow
Solution 23 - Javakishan maharanaView Answer on Stackoverflow