Pav*_*vel 2 jsf blob file-upload
如何将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>
Run Code Online (Sandbox Code Playgroud)
我的豆子
@Named
@ViewScoped
public class UploadPage {
private Part uploadedFile;
public void uploadFile(){
}
}
Run Code Online (Sandbox Code Playgroud)
SQL数据库BLOB类型在Java中表示为byte[].这在JPA中进一步注释为@Lob.所以,你的模型基本上需要看起来像这样:
@Entity
public class SomeEntity {
@Lob
private byte[] image;
// ...
}
Run Code Online (Sandbox Code Playgroud)
至于处理Part,你基本上需要把它读InputStream成一个byte[].Apache Commons IO IOUtils在这里很有帮助:
InputStream input = uploadedFile.getInputStream();
byte[] image = IOUtils.toByteArray(input); // Apache commons IO.
someEntity.setImage(image);
// ...
Run Code Online (Sandbox Code Playgroud)
或者,如果您更喜欢标准的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());
// ...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5677 次 |
| 最近记录: |