devdar
devdar

Reputation: 5654

SpringMVC Storing Base64

I have a Spring MVC application which has a registration form. This form has a picture in the format of base64 data. I would like to store this data in the database. Presently i am storing the base64 data in an input element. I have a few questions regarding this;

  1. what html element should i hold the base64 data in presently i am using an input element however i am getting an error on insert (Blob is the data type used in the Database and the 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

  2. Do i still need to use enctype="multipart/form-data" on the form tag even thought the data is in base64?

  3. If the base64 data is stored in held in html file element how do i preform validation on that to check if it is NULL?

Upvotes: 3

Views: 2911

Answers (2)

Chazz
Chazz

Reputation: 186

You might have put the path of the Blob e.g. <form:input path="theBlobField"> without adding a PropertyEditor for Blobs in your initBinder,

which means, you're trying to directly store a value of String type to Blob type - voila! IllegalStateException.

Possible approach is to create a PropertyEditor that converts your Base64 encoded String to a Blob type.

To decode the encoded String, you can use appache commons' Base64.decodeBase64 which returns an array of bytes then do your magic converting those bytes to Blob

Another solution is to forget about the path, use a simple <input name="photoData"> tag, then at the backend, just use request.getParameter("photoData") which gets the base64 encoded String data

One more thing, if things don't work, well maybe the encoded data starts with a mimeType declaration. 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);

Upvotes: 1

Markus Malkusch
Markus Malkusch

Reputation: 7868

You can use LobHelper to convert it to a Blob. You get the LobHelper from your hibernate session Session.getLobHelper().

As long as you don't have an <input type="file" />, there should be no need for enctype="multipart/form-data".

Validation should work as on ordinary String properties with @NotNull.

Personally I wouldn't store it encoded.

Upvotes: 1

Related Questions