How to Create API in Spring Boot to Upload Image
Posted By : Gaurav Prakash Ranjan | 31-Jul-2019
In this blog, I will explain how to create API using Spring Boot for uploading data and image from user to server in three steps.
1. Creating DTO And Entity Classe For Uploading Image And Data:
DTO class is used to sending and receiving data from the front-end and Entity class represents the actual data for storing data in the database.
/dto/DocumentDTO.java
import ... /** * Created By G.P.Ranjan **/ @JsonIgnoreProperties(ignoreUnknown = true) @Getter @Setter @NoArgsConstructor @EnableStringTrimer public class DocumentDTO { private Long id; @Valid @NotNull(message = "ENTER VALID DATA") private String name; private String bodyContentInHtml; private String documentLogo; public DocumentDTO(Long id,String name,String documentLogo,String bodyContentInHtml){ this.id=id; this.name=name; this.documentLogo=documentLogo; this.bodyContentInHtml=bodyContentInHtml; } @Override public String toString(){ return this.name; } }
/entity/Document.java
import ... /** * Created By G.P.Ranjan **/ @Entity @Getter @Setter @NoArgsConstructor public class Document{ @Column(columnDefinition = "text") private String name; @Column(columnDefinition = "text") private String documentLogo; @Column(columnDefinition = "text") private String bodyContentInHtml; public Document(Long id,String name,String DocumentLogo,String bodyContentInHtml){ super.id=id; this.name=name; this.documentLogo=documentLogo; this.bodyContentInHtml=bodyContentInHtml; } }
2. Creating Service Class For Uploading Images:
In the service, we write the actual code for performing API works. In this class, we write the code on how to handle request to save image and data.
/service/DocumentService.java
import .... /** * Created By G.P.Ranjan **/ @Service public class DocumentService { @Inject private DocumentRepository documentRepository; @Inject private ExceptionService exceptionService; public DocumentDTO createDocument(DocumentDTO documentDTO) { if(documentDTO.getName().equals("")){ exceptionService.duplicateDataException("Error Message"); } Document document = documentRepository.findByNameIgnoreCaseAndDeletedFalse(documentDTO.getName()); if (Optional.ofNullable(document).isPresent()) { exceptionService.duplicateDataException("Error Message"); } Document=new Document(DocumentDTO.getId(),DocumentDTO.getName(),DocumentDTO.getDocumentLogo(),DocumentDTO.getBodyContentInHtml()); DocumentRepository.save(Document); DocumentDTO.setId(Document.getId()); return DocumentDTO; } public Map uploadDocumentLogo(MultipartFile file){ File directory = new File(Document_LOGO_PATH); if (!directory.exists()) { try { directory.mkdir(); } catch (SecurityException se) { return null; } } String fileName = DateUtils.getCurrentDate().getTime() + file.getOriginalFilename(); final String path = Document_LOGO_PATH + File.separator + fileName; try (InputStream inputStream = file.getInputStream(); FileOutputStream fileOutputStream = new FileOutputStream(new File(path))) { byte[] buf = new byte[1024]; int numRead = 0; while ((numRead = inputStream.read(buf)) >= 0) { fileOutputStream.write(buf, 0, numRead); } } catch (Exception e) { return null; } Map responseResult = new HashMap<>(); responseResult.put("logoUrl",fileName); return responseResult; } }
3. Creating Controller Class For Uploading Image:
In this App, we created a DocumentController and coding for controlling the Request and call to Service Class.
/controllers/DocumentController.java
import ..... /** * Created By G.P.Ranjan **/ @RestController public class DocumentController { @Inject private DocumentService documentService; @ApiOperation("Save Document") @PostMapping(URL + "/document") public ResponseEntity createDocument(@RequestBody @Validated DocumentDTO DocumentDTO) { return ResponseHandler.generateResponse(HttpStatus.OK, true, documentService.createDocument(DocumentDTO)); } @ApiOperation("Upload Document Logo") @PostMapping(URL + "/document/logo") public ResponseEntity uploadDocumentLogo(@RequestParam("file") MultipartFile file) { return ResponseHandler.generateResponse(HttpStatus.OK, true, documentService.uploadDocumentLogo(file)); } }
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Gaurav Prakash Ranjan
Gaurav loves to learn new things, new technologies, he is a quick learner . He has good knowledge of Java.