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

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());
// ...
链接地址: http://www.djcxy.com/p/46216.html

上一篇: 如何从JSP页面中的数据库中检索和显示图像?

下一篇: 如何将Part转换为Blob,以便我可以将它存储在MySQL中?