How to store a html file in mysql using spring boot jpa?

I want to store an HTML file in MySQL DB so that for every user I can change the HTML tag with their name and email id from DB and replace that HTML file and render it?

Also, I need to store the Main sample HTML file in DB. Please help.

Add Comment
1 Answer(s)

I am assuming that you will send html file as form-data. Below is the code you can use

Entity

    @Id     @GeneratedValue(generator = "uuid")     @GenericGenerator(name = "uuid", strategy = "uuid2")     private String id;      private String fileName;      private String fileType;      @Lob     private byte[] data; 

Controller

public class FileHandlingController  {     @Autowired     FileHandlingService fileHandlingSgervice;          @PostMapping(value = "/upload")     @ResponseStatus(HttpStatus.ACCEPTED)     public FileInformation uploadDoc(@RequestParam("file") MultipartFile file) throws Exception     {         return fileHandlingSgervice.uploadDoc(file);     }      @GetMapping("/download/{fileId}")     public ResponseEntity<Resource> downloadFile(@PathVariable String fileId) throws Exception      {         return fileHandlingSgervice.downloadFile(fileId);     } } 

Service

public class FileHandlingService  {     @Autowired     DBFileStorageService dbFileStorageService;          public FileInformation uploadDoc(MultipartFile file) throws Exception      {         try         {             FileInformation fileUploadSuccessData = new FileInformation();             DBFile dbFile = dbFileStorageService.storeFile(file);             fileUploadSuccessData.setFileUUId(dbFile.getId());             fileUploadSuccessData.setFileName(dbFile.getFileName());             return fileUploadSuccessData;         }         catch(MaxUploadSizeExceededException e)         {             throw new Exception("File size too large. Max allowed size - 15 MB");         }         catch(Exception e)         {             throw new Exception("Error uploading file.");         }     }      public ResponseEntity<Resource> downloadFile(String fileId) throws Exception      {         try         {             DBFile dbFile = dbFileStorageService.getFile(fileId);             return ResponseEntity.ok()                 .contentType(MediaType.parseMediaType(dbFile.getFileType()))                 .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + dbFile.getFileName() + "\"")                 .body(new ByteArrayResource(dbFile.getData()));         }            catch(Exception e)         {             throw new Exception("Error downloading file");         }     }  } 
Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.