How to image File as Multipart File into the Database

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

How to image File as Multipart File into the Database

alagavat
I have a problem about converting the multipart file to byte[] array.

I wrote a code snippet but it didn't work. How can I fix it.

Here is the error shown below


Failed to convert property value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'byte[]' for property 'image';

Controller

public String saveEmployee(@ModelAttribute("employee") Employee theEmployee
            ,@RequestParam("file") MultipartFile file) throws IOException, ParseException {

    byte[] imageBytes = file.getBytes();

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

    theEmployee.setImage(imageBytes);

}

Employee Object

public class Employee implements Serializable{
....
@NotNull(message="is required")
@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;
}
 
}

Employee Forum

<form action="#" th:action="@{/employees/save}"
                                                 th:object="${employee}" method="POST" enctype="multipart/form-data">
<input type="file" name="image" th:field="*{image}"
                                        class="form-control mb-4 col-4" placeholder="Image">
...
</form>