How can I add multiple files with 2 fields in Springboot - java

My request DTO :
#Getter
#Setter
public class FileUploadRequestDTO {
private MultipartFile fileMap;
private String filetype;
private String fileNature;
}
// Controller method
#RequestMapping(path = FLAT_FILE_UPLOAD, method = RequestMethod.POST,
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<FileUploadResponseDTO> flatFileUpload(List<FileUploadRequestDTO> fileDTO){
}
**
Question:
I want to send multiple files with the following variables in the request body. How to achieve this in Postman?
**

Related

Map multipart data to POJO on Spring WebFlux

On the frontend we have a form which send the data as multipart/form-data and we need to receive the data in the controller. Keys nameconvention is to use hyphens.
We can receive the data in the controller by using #RequestPart annotation
#PostMapping(value = "/create", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Mono<String> create(#RequestPart("first-name") String firstName,
#RequestPart("last-name") String lastName) {
// ...
}
But the form can contains more fields, and in this case it is not so convenient to receive data by using #RequestPart.
Is there a way to map multipart fields to a POJO on Spring WebFLux? Something like
class UserData {
private String firstName;
private String lastName;
// getters & setters
}
#PostMapping(value = "/create", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Mono<String> create(UserData userData) {
// ...
}

Ignore json POJO fields not mapped in object in spring boot

I have pojo which has many fields. I have set value some field. But when i create json, whole pojo create a json . here is the code i have used:
Pojo
public class BasicInfoModel {
private String client_id="";
private String father_name="";
private String mother_name="";
private String gendar="";
//Getter and setter
}
Repository code
public BasicInfoModel getBasicInfo() {
BasicInfoModel lm = new BasicInfoModel();
lm.setFather_name("Enamul Haque");
return lm;
}
Controller code
#RequestMapping(value = "/get_donar_basic_info", method = RequestMethod.POST, produces ="application/json")
public #ResponseBody BasicInfoModel getBasicinfo(){
return repository.getBasicInfo();
}
But my json is resposne like bellow:
{
"client_id": "",
"father_name": "Enamul Haque",
"mother_name": "",
"gendar": ""
}
I have set value to father_name but i have seen that i have found all the value of pojo fields. I want get only set value of father_name and ignor other value which is not set in repository.
My json look like bellow: I will display only father_name.how to display bellow like json from above code?
{
"father_name": "Enamul Haque"
}
Please help me..
Json include non null values to ignore null fields when serializing a java class
#JsonInclude(Include.NON_NULL)
Jackson allows controlling this behavior at either the class level:
#JsonInclude(Include.NON_NULL)
public class BasicInfoModel { ... }
at the field level:
public class BasicInfoModel {
private String client_id="";
#JsonInclude(Include.NON_NULL)
private String father_name="";
private String mother_name="";
private String gendar="";
//Getter and setter
}
from jackson 2.0 use here use
#JsonInclude(JsonInclude.Include.NON_NULL)
You can also ignore the empty values
#JsonInclude(JsonInclude.Include.NON_EMPTY)
Add the #JsonIgnoreProperties("fieldname") annotation to your POJO.
Or you can use #JsonIgnore before the name of the field you want to ignore while deserializing JSON. Example:
#JsonIgnore
#JsonProperty(value = "client_id")
#RequestMapping(value = "/get_donar_basic_info", method = RequestMethod.POST, produces ="application/json")
public #ResponseBody BasicInfoModel getBasicinfo(){
return repository.getBasicInfo();
}
You can ignore field at class level by using #JsonIgnoreProperties annotation and specifying the fields by name:
#JsonIgnoreProperties(value = { "client_id" })
public class BasicInfoModel {
private String client_id="";
private String father_name="";
private String mother_name="";
private String gendar="";
//Getter and setter
}
Or you can use #JsonIgnore annotation directly on the field.
public class BasicInfoModel {
#JsonIgnore
private String client_id="";
private String father_name="";
private String mother_name="";
private String gendar="";
//Getter and setter
}
You can read here more about this.

Spring Boot multiple files upload with multiple objects

I need help I last time create the controller with the single file upload with an object and it's work for me like
My POJO class
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({ "file", "data" })
public class FileWithObject<T> {
#JsonProperty("file")
private MultipartFile file;
#JsonRawValue
#JsonProperty("data")
private T data;
}
MY REST CONTOLLER
#RequestMapping(value="/filestore/{bucket-uuid}/appsport.com/singleFileUploadWithObject/{folder}",
method = RequestMethod.POST)
#ResponseBody
// api work
public String singleFileUploadWithObject(
#PathVariable(name="bucket-uuid", required = true) String bucketUUId,
#PathVariable(name="folder", required = false) String folder,
FileWithObject rawData) {
return pingResponse;
}
My Postman result
That's all work for me. How to send the list of the objects through the postman or is possible to handle that way request like below rest controller
#RequestMapping(value="/filestore/{bucket-uuid}/appsport.com/listOfObjectsWithSingleFile/{folder}", method = RequestMethod.POST)
#ResponseBody
public String listOfObjectsWithSingleFile(
#PathVariable(name="bucket-uuid", required = true) String bucketUUId,
#PathVariable(name="folder", required = false) String folder,
Set<FileWithObject> rawData) {
return pingResponse;
}
How to handle list of objects
[{
"file": fileobject,
"data": "zyz"
},{
"file": fileobject,
"data": "zyz"
}]
I'm trying to creating the api for this blow task
I have done this by use of Meta-Data concept there are few changes I did in controller and bean
Controller
#RequestMapping(value="/filestore/{bucket-uuid}/appsport.com/listOfObjectsWithSingleFile/{folder}",
method = RequestMethod.POST)
#ResponseBody
public String listOfObjectsWithSingleFile(
#PathVariable(name="bucket-uuid") String bucketUUId, #PathVariable(name="folder") String folder,
FileWithObject objects) { // change this Set<FileWithObject> rawData to FileWithObject objects
return pingResponse;
}
Bean
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({ "file", "files", "data" })
public class FileWithObject<T> {
#JsonProperty("file")
private MultipartFile file;
#JsonProperty("files")
private List<MultipartFile> files;
#JsonRawValue
#JsonProperty("data")
private T data;
// work like (meta-data)
List<FileWithObject> rawData;
// getter setter
}
Image's For Request
Note:- I'm Still looking for this issue handle this in a blow way
#RequestMapping(value="/filestore/{bucketuuid}/appsport.com/listOfObjectsWithSingleFile/{folder}", method = RequestMethod.POST)
#ResponseBody
public String listOfObjectsWithSingleFile(#PathVariable(name="bucket-uuid", required = true) String bucketUUId,
#PathVariable(name="folder", required = false) String folder,Set<FileWithObject> rawData) {
return pingResponse;
}
hope it helps some one

Spring Data REST - RepositoryEventHandler methods not getting invoked for POST method?

I have the following domain object and DTO defined.
Country.java
#Data
#Entity
public class Country extends ResourceSupport {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long countryID;
#NotBlank(message = "Country name is a required field")
private String countryName;
private String countryNationality;
}
CountryDTO.java
#Data
public class CountryDTO {
private List<Country> countries;
}
I have overridden the POST method in the RepositoryRestController for the country class.
#RepositoryRestController
public class CountryController {
#Autowired
private CountryRepository repo;
#RequestMapping(method = POST, value = "countries")
public #ResponseBody ResponseEntity<?> createCountry(#RequestBody Resource<CountryDTO> dto,
Pageable page, PersistentEntityResourceAssembler resourceAssembler) {
Country savedCountry = repo.save(dto.getContent().getCountries());
return new ResponseEntity<>(resourceAssembler.toResource(savedCountry), HttpStatus.OK);
}
}
Now I have defined a RepositoryEventHandler to handle validations.
#Component
#RepositoryEventHandler
public class CountryHandler {
#HandleBeforeCreate
public void handleBeforeCreate(Country country) {
System.out.println("testing");
}
But when I send a POST request to the endpoint http://localhost:8080/countries, the eventhandler does not get invoked. Is there anything I am doing wrong?
UPDATE 1:
I am sending the following JSON to the endpoint using Postman.
"countries":[{
"countryName":"Australia",
"countryNationality":"Australian"
}]
It is difficult to give you an exact solution not knowing how you are invoking the request. But possible reason is that you are missing the slash symbol #RequestMapping value attribute:
#RequestMapping(method = POST, value = "countries")
Should be:
#RequestMapping(method = POST, value = "/countries")
Define a Bean in AppConfigration as
#Configuration
#EnableAsync
public class AppConfig {
#Bean
CountryHandler countryHandler (){
return new CountryHandler ();
}
}
It will work then.
Try editing maybe the Controller class annotation from:
#RepositoryRestController
to
#RestController
and mainly the method annotation from:
#RequestMapping(method = POST, value = "countries")
to
#RequestMapping(value = "/countries", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
PS: produces = MediaType.APPLICATION_JSON_VALUE if you are going to return json.
I know this is older but this works as it is supposed to.
The methods defined in a #RepositoryRestController implementation replace the methods in the default RepositoryEntityController which publish #RepositoryEventHandler events.
So your controller needs to publish a create event:
#RepositoryRestController
public class CountryController {
#Autowired
private CountryRepository repo;
private final ApplicationEventPublisher publisher; //This changed
#RequestMapping(method = POST, value = "countries")
public #ResponseBody ResponseEntity<?> createCountry(#RequestBody Resource<CountryDTO> dto,
Pageable page, PersistentEntityResourceAssembler resourceAssembler) {
Country savedCountry = repo.save(dto.getContent().getCountries());
publisher.publishEvent(new BeforeCreateEvent(savedCountry)); //This changed
return new ResponseEntity<>(resourceAssembler.toResource(savedCountry), HttpStatus.OK);
}
}

GET request with nested objects in #RestController?

Is it possible to create a GET webservice in spring and using nested properties in the query? Like search.limitResults in the following example:
localhost:8080/firstname=test&search.limitResults=10
You get the idea. Can this be achieved?
#RestController
public class MyServlet {
#RequestMapping(value = "/", method = RequestMethod.GET)
private String test(RestParams p) {
}
}
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class RestParams {
private String firstname;
private String lastname;
//is that possible to nest?
private Search search;
}
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Search {
private int limitResults;
//some more
}
To answer my own question: it just works this way! Nested properties can be accessed using the dot accessor, like search.limitResults.

Categories

Resources