Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(){
    }
}
like image 300
Pavel Avatar asked Dec 22 '25 05:12

Pavel


1 Answers

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

like image 127
BalusC Avatar answered Dec 24 '25 05:12

BalusC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!