Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multipart File upload using Springfox and Swagger-ui

I'm using Spring MVC as a rest controller and I've integrated Swagger-ui with my controller using Springfox. I'd like to have a method that is able to upload a file via the Swagger-ui interface. I only need two parameters, a long acting for an object id and the file to be uploaded.

@RestController
public class controller{
    @RequestMapping(value="/upload", method=RequestMethod.POST)
    public void uploadFile(@RequestParam Long id,
                           @RequestParam MultipartFile file){
          //do some stuff
    }
}

I've tried almost everything and I can't get a file upload button to appear. However, if I do:

@RestController
public class Controller{
    @RequestMapping(value="/upload", method=RequestMethod.POST)
    public void uploadFile(@RequestParam Long id,
                           @RequestPart File file){
         //do some stuff
    }
}

The file upload button appears, but it always throws http code 415 when trying to upload a file. Besides, I need the input to be a MultipartFile, not a regular File. Even if I use the @RequestPart annotation with Multipart File, the choose file to upload button does not appear. How can I get this to work???? Even:

@RestController
public class Controller{
    @RequestMapping(value="/upload", method=RequestMethod.POST)
    public void uploadFile(@RequestPart String metaData,
                           @RequestPart MultipartFile file){
        //do some stuff
    }
}

Won't work. If someone could give a walkthrough of how to get this button to appear for MultipartFile? I'd be forever grateful.

like image 899
drumlord Avatar asked Jul 15 '15 01:07

drumlord


People also ask

How do you send a multipart file in request body in swagger?

You start with the requestBody/content keyword. Then, you specify the media type of request data. File uploads typically use the multipart/form-data media type, and mixed-data requests usually use multipart/mixed . Below the media type, put the schema keyword to indicate that you start describing the request payload.

How do I send a file using swagger?

In Swagger 2.0 (OpenAPI Specification 2.0), use a form parameter ( in: formData ) with the type set to file. Additionally, the operation's consumes must be multipart/form-data .


1 Answers

I think you are missing the consumes attribute of the @RequestMapping in your second snippet. See the following example

@RequestMapping(
    path = "/upload", 
    method = RequestMethod.POST, 
    consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> handleUpload(
        @RequestPart("file") MultipartFile file, 
        @RequestParam("someId") Long someId,         
        @RequestParam("someOtherId") Long someOtherId) { 
    return new ResponseEntity<>();
}
like image 153
abedurftig Avatar answered Oct 07 '22 12:10

abedurftig