primefaces 文件上传下载的配置

来源:互联网 发布:telnet的端口号 编辑:程序博客网 时间:2024/05/22 00:26

结合了几篇外国友人的帖子和primefaces文档:

一、上传

1、在web.xml中添加

<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>auto|native</param-value>
</context-param>

本人亲测commons不可用,就算加入filter

2.1 简单方式上传

<h:form enctype="multipart/form-data">
    <p:fileUpload value="#{fileBean.file}" mode="simple" />
    <p:commandButton value="Submit" ajax="false"/>
</h:form>

这个是针对mode=simple的上传方案,如果mode=advanced,去掉enctype="multipart/form-data"不然界面会出现错误
这里,commandButton的ajax必须是false

2.2 高级方式上传

            <p:panelGrid columns="2">
                <h:outputLabel for="image" value="Select Image: *" />
                <p:fileUpload  fileUploadListener="#{productBean.handleFileUploadx}" mode="advanced" label="选择文件" uploadLabel="点此上传" cancelLabel="取消" allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/> 

                <f:facet name="footer">
                    <p:commandButton value="Submit"  >
                        <f:ajax render="testimg"/>
                    </p:commandButton>
                </f:facet>
            </p:panelGrid>
3、得到byte[]

前台

            <p:graphicImage id="testimg" value="#{productBean.image}" width="50" height="50" style="">
            </p:graphicImage>

后台


    private StreamedContent image;

    get

    set

    public void handleFileUploadx(FileUploadEvent event) {
        UploadedFile f=event.getFile();
        setFile( event.getFile());
        try {
            InputStream stream;
            stream = file.getInputstream();
            byte[] bt=IOUtils.toByteArray(stream);
            ByteArrayInputStream img=new ByteArrayInputStream(bt);
            setImage( new DefaultStreamedContent(img,"image/jpg"));
        } catch (IOException ex) {
            Logger.getLogger(ProductBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

这里 IOUtils是Apache的common-io在本人的资源中提供下载,当然,得到字节流之后你可以把它存入数据库,需要的时候在取出来,我这里只是展示了上传完文件之后显示上传文件的功能。

如果你想把上传的file保存成文件

               InputStream stream=file.getInputstream();
                FileOutputStream fos=new FileOutputStream(new File("/dd.jpg"));
                int read=0;
                byte[] bytes=new byte[1024];
                while((read=stream.read(bytes))!=-1)
                {
                    fos.write(bytes,0,read);
                }

二、下载

 前台

<p:commandLink value="Download" ajax="false">
<p:fileDownload value="#{fileBean.downfile}"/>
</p:commandLink>

后台

初始化的时候
             InputStream stream = this.getClass().getResourceAsStream("./ok.png");
            setDownfile(new DefaultStreamedContent(stream, "image/jpeg","dx.jpg"));

这样,就可以把上传资源以二进制的方式存入数据库,需要下载的时候,在从数据库中取出以提供下载。

三、实体类的二进制表示

@Lob

private byte[] file;

set

get

0 0
原创粉丝点击