0

I couldn't handle with inserting image file into the database. I could write a code snippet related with inserting process in the controller part.

I could use base64encode process for image.

I could define image as a byte part because I define image as Blob in the database part.

How can I do the process if it isn't right.

Controller part

@PostMapping("/saveCustomer") // @RequestMapping(path = "/saveCustomer", method = RequestMethod.POST)
    public String saveCustomer(@ModelAttribute("customer") Customer theCustomer,@RequestParam("image") MultipartFile file) {

        System.out.println("/saveCustomer | File Name : "+file.getName());


        byte[] imageBytes = new byte[(int) file.getSize()];

        try {
            FileInputStream fileInputStream = new FileInputStream(file.getOriginalFilename());
            fileInputStream.read(imageBytes);
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        theCustomer.setImage(imageBytes);


        // save the customer using our service
        customerService.saveCustomer(theCustomer);


        return "redirect:/customer/list";
    }

Customer class

    public class Customer implements Serializable{

        @Id
        @SequenceGenerator(name="CUSTOMER_SEQ", sequenceName="CUSTOMER_SEQ", allocationSize=1)
        @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="CUSTOMER_SEQ")
        @Column(name="ID", nullable = false)
        private int id;

        @Column(name="FIRSTNAME")
        private String firstName;

        @Column(name="LASTNAME")
        private String lastName;

        @Column(name="EMAIL")
        private String email;

        @Column(name="IMAGE")
        private byte[] image;

        @Transient
        private String base64Image;

public byte[] getImage() {
        return image;
    }

    public void setImage(byte[] image) {
        this.image = image;
    }

public String getBase64Image() {
        base64Image = Base64.getEncoder().encodeToString(this.image);
        return base64Image;
    }

    public void setBase64Image(String base64Image) {
        this.base64Image = base64Image;
    }

    ...
    }

html part

<tr>
    <td>Image:</td>
    <td><input type="file" name="photo" required="required"/>
    </td>
</tr>
S.N
  • 2,157
  • 3
  • 29
  • 78

1 Answers1

1

You should take a look at the community project called Spring Content.

This project provides an abstraction over various different types of storage for Spring Resources.

It provides a programming model very similar to Spring Data and therefore you get a lot of boilerplate implementation for free. There is no need to define your own controller implementation for example.

There are getting started guides here and examples for various different databases here. A combination of spring-content-jpa and spring-content-rest will be enough. There is also a good example answer here.

Paul Warren
  • 2,411
  • 1
  • 15
  • 22