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(){
    }
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Pavel
  • 1,278
  • 2
  • 17
  • 34
  • see the following link about how to save blob image in database http://jsfspotlight.blogspot.com/2013/09/ejb3jsf2primfacesuploading-and.html – hanan Ahmed Oct 02 '13 at 15:17

1 Answers1

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

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • I downloaded the library from http://apache.igor.onlinedirect.bg//commons/io/binaries/commons-io-2.4-bin.zip, 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 02 '13 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 02 '13 at 14:52