SpringMVC Base64 Storage

I have a Spring MVC application that has a registration form. This form has an image in base64 data format. I would like to store this data in a database. I am currently storing base64 data in an input element. I have several questions regarding this:

  • which html element should contain base64 data, I am currently using an input element, however I am getting an error when inserting (Blob is the datatype used in database and Java object) -

    Failed to convert property value of type java.lang.String to required type java.sql.Blob for property photo; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.sql.Blob] for property photo: no matching editors or conversion strategy found

    OR is there a way to convert String to BLOB in java

  • Should I use enctype = "multipart / form-data" on the form tag even if the data is in base64?

  • If base64 data is stored in the html file, how can I check if validation is correct to check if it is NULL?

+3


source to share


2 answers


You can use LobHelper

to convert it to Blob

. You get LobHelper from hibernate session Session.getLobHelper()

.

Until you have it <input type="file" />

, there is no need for enctype = "multipart / form-data".



Validation should work like normal String properties with @NotNull.

Personally, I will not store it in encoding.

+1


source


You might have posted a path

Blob for example. <form:input path="theBlobField">

no adding PropertyEditor

for Blobs in initBinder

,

which means you are trying to directly store a String to BLOB - voila! IllegalStateException.

A possible approach is to create PropertyEditor

one that converts your Base64 encoding to Blob type.

To decode the encoded string you can use appost commons' Base64.decodeBase64

which returns an array of bytes and then your magic converts those bytes to Blob



Another solution is to forget about the path, use a simple tag <input name="photoData">

and then on the backend just use request.getParameter("photoData")

which receives the base64 encoded string data

One more thing, if something doesn't work, perhaps the encoded data starts with a declaration mimeType

. To remove it use

//@RequestParam data
//remove mimeType declaration in the data string first
String byteStr = data.split(",")[1];


//get the byte array of the data
byte[] bytes = Base64.decodeBase64(byteStr);

      

+1


source







All Articles