如何将 Part 转换为 Blob,以便我可以将其存储在 MySQL 中? [英] How to convert Part to Blob, so I can store it in MySQL?

查看:12
本文介绍了如何将 Part 转换为 Blob,以便我可以将其存储在 MySQL 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 Part 转换为 Blob,以便我可以将其存储在 MySQL 中?它是一个图像.谢谢

How to convert Part to Blob, so I can store it in MySQL? It is an image. Thank you

我的表格

<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>

我的豆子

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

    public void uploadFile(){
    }
}

推荐答案

SQL 数据库 BLOB 类型在 Java 中表示为 byte[].这在 JPA 中被进一步注释为 @Lob.因此,您的模型基本上需要如下所示:

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;

    // ...
}

对于Part的处理,基本上需要将它的InputStream读入byte[].Apache Commons IO IOUtils 在这里很有帮助:

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);
// ...

或者,如果您更喜欢标准的 Java API,它只是稍微冗长一点:

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());
// ...

这篇关于如何将 Part 转换为 Blob,以便我可以将其存储在 MySQL 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆