如何将Part转换为Blob,以便我可以将其存储在MySQL中?

3
如何将Part转换为Blob,以便可以在MySQL中存储它?它是一张图片。 谢谢。
我的表单
<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>

我的Bean

@Named
@ViewScoped
public class UploadPage {       
    private Part uploadedFile; 

    public void uploadFile(){
    }
}

请查看以下链接,了解如何将Blob图像保存在数据库中:http://jsfspotlight.blogspot.com/2013/09/ejb3jsf2primfacesuploading-and.html - hanan Ahmed
1个回答

9

在Java中,SQL数据库的BLOB类型表示为byte[]。在JPA中,它进一步被注释为@Lob。因此,您的模型基本上应该像这样:

@Entity
public class SomeEntity {

    @Lob
    private byte[] image;

    // ...
}

处理Part时,您基本上需要将其InputStream读入byte[]。您可以使用InputStream#readAllBytes()方法:

InputStream input = uploadedFile.getInputStream();
byte[] image = input.readAllBytes();
someEntity.setImage(image);
// ...
entityManager.persist(someEntity);

如果您尚未升级到Java 9,请前往将InputStream转换为byte数组的替代方法了解读取InputStreambyte []的其他方法。


我从http://apache.igor.onlinedirect.bg//commons/io/binaries/commons-io-2.4-bin.zip下载了库,并将jar文件加载到我的项目中。我像这样导入它`import org.apache.commons.io.*;`,但它告诉我找不到它... - Pavel
只需将JAR文件放入“/WEB-INF/lib”文件夹中即可。千万不要在项目属性中胡乱操作,尤其是Build Path之类的。如果之前已经进行过这样的操作,请确保将其全部撤销。顺便说一句,我编辑了我的答案,以展示标准的Java API方法。 - BalusC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接