Postman: Required request part 'file' is not present
Asked Answered
L

9

16

I wanted to upload an image to my Rest API through postman. I am using spring boot framework. Here is the screen shot:

enter image description here

I also have not set any any headers as I found in other stack overflow answers that it gives multipart boundary error.

Now, below is my controller code:

package com.practice.rest.assignment1.controller;

import java.io.IOException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.practice.rest.assignment1.model.Product;
import com.practice.rest.assignment1.service.CatalogueService;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

@RestController
@RequestMapping("/CatalogueController/")
public class CatalogueController{

    @Autowired
    private CatalogueService catalogueService;

    @RequestMapping(value = "addProduct", method = RequestMethod.POST , consumes = "multipart/form-data")
    public Product addProduct(@RequestParam String productJson, @RequestParam MultipartFile file) throws JsonParseException, JsonMappingException, IOException {


        Product product = new ObjectMapper().readValue(productJson, Product.class);
        byte[] mediaBytes = file.getBytes();
        product.setImage(mediaBytes);
        return catalogueService.saveInDb(product);

    }

}

Now, I am taking a Product object which consists internally an image defined as byte[] array. I take this as string and image separately as Multipart file.

Below is my product class attributes defined :

    private Long pId;
    private String model;
    private String brand;
    private byte[] image; // This is where I want the image to save
    private Long price;
    private String currency;
    private String transmissionType;
    private String fuelType;

Since , I am using spring boot , here is my Main class :

package com.practice.rest.assignment1;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
public class App {

  public static void main(String[] args) {
      SpringApplication.run(App.class, args);  
  }

}

The error on postman I get is :

{
  "timestamp": 1478611635977,
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.web.multipart.support.MissingServletRequestPartException",
  "message": "Required request part 'file' is not present",
  "path": "/CatalogueController/addProduct"
}

Where am I wrong ?

Loveinidleness answered 8/11, 2016 at 13:48 Comment(0)
T
4

I think the problem lies in the JSON parameter you are sending. In postman you don't need to put the starting and trailing " to represent a parameter as string. And also if you use starting and ending " then inside the JSON( mean for JSON object the properties key and value) you should use '(single quote).

Trishatriskelion answered 8/11, 2016 at 14:49 Comment(1)
I just needed to remove starting and ending double quotes . It's so strange that error was being thrown on file request part. Thanks !!Loveinidleness
K
6

Try remove 'Content-Type: multipart/form-data...', section of the headers. It solved this for me.

Kinnikinnick answered 11/5, 2017 at 7:52 Comment(0)
T
4

I think the problem lies in the JSON parameter you are sending. In postman you don't need to put the starting and trailing " to represent a parameter as string. And also if you use starting and ending " then inside the JSON( mean for JSON object the properties key and value) you should use '(single quote).

Trishatriskelion answered 8/11, 2016 at 14:49 Comment(1)
I just needed to remove starting and ending double quotes . It's so strange that error was being thrown on file request part. Thanks !!Loveinidleness
P
2

Hi @Breaking Benjamin I did a same demo, and there is my post request copy:

curl 'http://localhost:9999/api/v1/upload' -H 'Pragma: no-cache' \
-H 'Origin: chrome-extension://fdmmgilgnpjigdojojpjoooidkmcomcm' \
-H 'Accept-Encoding: gzip, deflate, br' \
-H 'Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.6,en;q=0.4' \
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36' \
-H 'Content-Type: multipart/form-data; boundary=----WebKitFormBoundary0ae4CymwYLjdqdI1' \
-H 'Accept: */*' -H 'Cache-Control: no-cache' \
-H 'Cookie: _ga=GA1.1.433565887.1474948752' \ 
-H 'Connection: keep-alive' -H 'DNT: 1' --data-binary $'------WebKitFormBoundary0ae4CymwYLjdqdI1\r\nContent-Disposition: form-data; name="file"; filename="228cb73.jpg"\r\nContent-Type: image/jpeg\r\n\r\n\r\n------WebKitFormBoundary0ae4CymwYLjdqdI1\r\nContent-Disposition: form-data; name="a"\r\n\r\n123\r\n------WebKitFormBoundary0ae4CymwYLjdqdI1--\r\n' --compressed

And, my upload controller is written like this:

@RequestMapping(method = RequestMethod.POST)
    public ResponseEntity handleUpload(
            @RequestParam("a")String a,
            @RequestParam("file") MultipartFile multipartFile) throws IOException {

        System.out.println(a);
        ...

In my console, the param a is successfully output:

param a output

Even if I use a json string to send request again:

curl 'http://localhost:9999/api/v1/upload' -H 'Pragma: no-cache' -H 'Origin: chrome-extension://fdmmgilgnpjigdojojpjoooidkmcomcm' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.6,en;q=0.4' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36' -H 'Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryBTudL55M6S8ENLVt' -H 'Accept: */*' -H 'Cache-Control: no-cache' -H 'Cookie: _ga=GA1.1.433565887.1474948752' -H 'Connection: keep-alive' -H 'DNT: 1' --data-binary $'------WebKitFormBoundaryBTudL55M6S8ENLVt\r\nContent-Disposition: form-data; name="file"; filename="228cb73.jpg"\r\nContent-Type: image/jpeg\r\n\r\n\r\n------WebKitFormBoundaryBTudL55M6S8ENLVt\r\nContent-Disposition: form-data; name="a"\r\n\r\n"{"key":"value"}"\r\n------WebKitFormBoundaryBTudL55M6S8ENLVt--\r\n' --compressed

It's looks your code is ok, but would you try to use curl to send a request again, maybe this is because you bad usage of postman.

Pyelitis answered 8/11, 2016 at 15:3 Comment(0)
R
2

For me it worked to set these variables in application.properties:

spring.http.multipart.enabled=true 
spring.http.multipart.location= /upload
Riojas answered 16/4, 2018 at 17:53 Comment(2)
/upload uses a relative path to uploaded files, it can be helpful: code @ConfigurationProperties("storage") public class StorageProperties { /** * Folder location for storing files */ private String location = "your/absolute/path"; public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } } codeMichaelis
In the Springboot Example: spring.io/guides/gs/uploading-files It had the following: spring.servlet.multipart.max-file-size=128KB spring.servlet.multipart.max-request-size=128KB spring.http.multipart.enabled=false Changing the enabled=false to true (as per you answer) fixed the 'file' is not present problem for me. Thx!Funicular
C
1

For me updating my application.properties by updating variable worked spring.http.multipart.enabled=true

My service is

@PostMapping(value = "/console")
public ResponseEntity<RxConsoleDTO> addRxConsole(@RequestParam("attachment") MultipartFile attachmentFile,  @RequestParam("type") String type) throws IOException {// your logic}

enter image description here

Civies answered 1/5, 2018 at 8:54 Comment(0)
L
1

I had the same problem and it turned to be not the problem with Postman itself. I added MultipartResolver bean and it solved the problem -

@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    multipartResolver.setMaxUploadSize(-1);
    return multipartResolver;
}
Lilia answered 6/10, 2021 at 16:11 Comment(0)
E
0

Also check if the below property is enabled and if we are uploading a text file it won't consider as proper parameter.

upload.file.extensions=jpg, jpeg, gif, png
Extract answered 18/5, 2019 at 2:6 Comment(0)
S
0

I just bumped into your question as I faced the same error too. Note: I was writing a pyTest to test my API.

I just deleted the following lines from the file

'Content-Type': 'multipart/form-data; boundary=--------------------------561045520875406684819091',
'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW',

And, it worked :)

Syllabism answered 21/1, 2021 at 14:11 Comment(0)
K
0

If like for me, none of the solutions worked for you, check your postman log for errors. There might be some issue with Postman loading the file to upload

Kris answered 14/6 at 8:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.