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.
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.
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 .
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<>();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With