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

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

问题描述

如何将Part转换为Blob,这样我就可以将它存储在MySQL中?这是一个图像。
谢谢

我的表单

 < h :form id =formenctype =multipart / form-data> 
< h:messages />
< h:panelGrid columns =2>
< h:outputText value =File:/>
< h:inputFile id =filevalue =#{uploadPage.uploadedFile}/>
< / h:panelGrid>
< br />< br />
< h:commandButton value =上传文件action =#{uploadPage.uploadFile}/>
< / h:表格>

我的bean

  @Named 
@ViewScoped
public class UploadPage {
private part uploadedFile;
$ b $ public void uploadFile(){
}
}


byte [] 。这是在JPA进一步被注释为 @Lob 。所以,你的模型基本上需要像这样:

$ p $ @Entity
public class SomeEntity {

@Lob
私人字节[]图片;

// ...
}

Part ,你基本上需要将它的 InputStream 读入 byte [] 。 Apache Commons IO IOUtils 在这里很有用:

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

或者如果您更喜欢标准的Java API,更详细:

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


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

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

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