Search code examples
jsffile-uploadblob

How to convert Part to Blob, so I can store it in MySQL?


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(){
    }
}

Solution

  • 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[].