3

How to convert Part to Blob, so I can store it in MySQL? It is an image. Thank you

My form

<h:form id="form" enctype="multipart/form-data">
        <h:messages/>
        <h:panelGrid columns="2">
            <h:outputText value="File:"/>
            <h:inputFile id="file" value="#{uploadPage.uploadedFile}"/>
        </h:panelGrid>
        <br/><br/>
        <h:commandButton value="Upload File" action="#{uploadPage.uploadFile}"/>
</h:form>

My bean

@Named
@ViewScoped
public class UploadPage {       
    private Part uploadedFile; 

    public void uploadFile(){
    }
}
1

1 Answer 1

9

The SQL database BLOB type is in Java represented as byte[]. This is in JPA further to be annotated as @Lob. So, your model basically need to look like this:

@Entity
public class SomeEntity {

    @Lob
    private byte[] image;

    // ...
}

As to dealing with Part, you thus basically need to read its InputStream into a byte[]. You can use InputStream#readAllBytes() for this:

InputStream input = uploadedFile.getInputStream();
byte[] image = input.readAllBytes();
someEntity.setImage(image);
// ...
entityManager.persist(someEntity);

Or if you're not on Java 9 yet, then head to Convert InputStream to byte array in Java for alternative ways to read an InputStream into a byte[].

2
  • I downloaded the library from apache.igor.onlinedirect.bg//commons/io/binaries/…, and loaded the jar file in my project. I imported it like this import org.apache.commons.io.*;, but it tells me that it could not find it.....
    – Pavel
    Oct 2, 2013 at 14:48
  • Just drop JAR file in /WEB-INF/lib folder. Do not fiddle around in project's properties, for sure not Build Path and likes. If you did it before, make sure that you undo it all. By the way, I edited my answer to show the standard Java API approach.
    – BalusC
    Oct 2, 2013 at 14:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.