Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
681 views
in Technique[技术] by (71.8m points)

jsf - 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(){
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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[]. Apache Commons IO IOUtils is helpful here:

InputStream input = uploadedFile.getInputStream();
byte[] image = IOUtils.toByteArray(input); // Apache commons IO.
someEntity.setImage(image);
// ...

Or if you prefer standard Java API which is only a bit more verbose:

InputStream input = uploadedFile.getInputStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[10240];
for (int length = 0; (length = input.read(buffer)) > 0;) output.write(buffer, 0, length);
someEntity.setImage(output.toByteArray());
// ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...