在JSF中显示上传的图像

时间:2012-07-16 14:46:44

标签: file-upload jsf-2 primefaces graphicimage

我有一个视图范围的bean,我创建了一个人。一个人可以有一张照片。此图片上传了创建此人的同一页面。图片未存储在数据库或磁盘上(因为尚未创建此人)。 bean必须是视图范围的,因为可以在别处创建一个人,并且它使用相同的bean。如果bean是会话作用域并且用户上传图片但没有保存该人,则下次用户尝试创建人时将显示该图片。

我通过使用两个豆来解决这个问题;一个视图作用域创建人和一个会话作用域bean来上传图片并将图片作为流。然而,这会引起上述问题。

如何以更好的方式解决这个问题?

上传bean:

@ManagedBean(name = "uploadBean")
@SessionScoped
public class UploadBean
{
    private UploadedFile    uploadedFile;

    public UploadedFile getUploadedFile()
    {
        return uploadedFile;
    }

    public StreamedContent getUploadedFileAsStream()
    {
        if (uploadedFile != null)
        {
            return new DefaultStreamedContent(new ByteArrayInputStream(uploadedFile.getContents()));
        }
        return null;
    }

    public void uploadFile(FileUploadEvent event)
    {
        uploadedFile = event.getFile();
    }
}

create-a-person bean:

@ManagedBean(name = "personBean")
@ViewScoped
public class PersonBean
{
    private Person newPerson = new Person();

    public Person getNewPerson()
    {
        return newPerson;
    }

    private UploadedFile getUploadedPicture()
    {
        FacesContext context = FacesContext.getCurrentInstance();
        ELContext elContext = context.getELContext();
        UploadBean uploadBean = (UploadBean) elContext.getELResolver().getValue(elContext, null, "uploadBean");
        return uploadBean.getUploadedFile();
    }

    public void createPerson()
    {
        UploadedFile uploadedPicture = getUploadedPicture();
        // Create person with picture;
    }
}

相关的JSF页面部分:

<h:form enctype="multipart/form-data">
    <p:outputPanel layout="block" id="personPicture">
        <p:graphicImage height="150"
            value="#{uploadBean.uploadedFileAsStream}"
            rendered="#{uploadBean.uploadedFileAsStream != null}" />
    </p:outputPanel>
        <p:fileUpload auto="true" allowTypes="/(\.|\/)(gif|jpe?g|png)$/"
            fileUploadListener="#{uploadBean.uploadedFile}"
            update="personPicture" />
    <p:commandButton value="Save" actionListener="#{personBean.createPerson()}"/>
</h:form>

3 个答案:

答案 0 :(得分:4)

我采取了不同的方法。我最初是为了显示上传的图片,但是如果还没有创建Person,那么将它保留在客户端就好了。我找到this question并根据所选答案创建了以下内容:

在头部我包括html5shiv如果浏览器是IE并且版本小于9以获得兼容性:

<h:outputText value="&lt;!--[if lt IE 9]&gt;" escape="false" />
<h:outputScript library="js" name="html5shiv.js" />
<h:outputText value="&lt;![endif]--&gt;" escape="false" />

要显示/上传图像我有以下元素:

<p:fileUpload binding="#{upload}" mode="simple"
    allowTypes="/(\.|\/)(gif|jpe?g|png)$/"
    value="#{personBean.uploadedPicture}"/>
<p:graphicImage value="#" height="150" binding="#{image}" />

还有一些JavaScript / jQuery魔术:

function readPicture(input, output)
{
    if (input.files && input.files[0])
    {
        var reader = new FileReader();
        reader.onload = function(e)
        {
            output.attr('src', e.target.result);
        };
        reader.readAsDataURL(input.files[0]);
    }
}

$("[id='#{upload.clientId}']").change(
    function()
    {
        readPicture(this, $("[id='#{image.clientId}']"));
    });

uploadedPicture属性现在是一个简单的属性:

@ManagedBean(name = "personBean")
@ViewScoped
public class PersonBean
{
    private UploadedFile uploadedPicture;

    public UploadedFile getUploadedPicture()
    {
        return uploadedPicture;
    }

    public void setUploadedPicture(UploadedFile uploadedPicture)
    {
        this.uploadedPicture = uploadedPicture;
    }
}

答案 1 :(得分:3)

Add.xhtml

<h:form id="add-form" enctype="multipart/form-data">
         <p:growl id="messages" showDetail="true"/>
         <h:panelGrid columns="2">
              <p:outputLabel for="choose" value="Choose Image :" />
              <p:fileUpload id="choose" validator="#{productController.validateFile}" multiple="false" allowTypes="/(\.|\/)(gif|jpe?g|png)$/"  value="#{productController.file}" required="true" mode="simple"/>
            <p:commandButton value="Submit" ajax="false" update="messages" id="save-btn" actionListener="#{productController.saveProduct}"/>
         </h:panelGrid>
</h:form>

这是Managed Bean Code:

@ManagedBean
@RequestScoped
public class ProductController implements Serializable{
    private ProductBean bean;
    @ManagedProperty(value = "#{ProductService}")
    private ProductService productService;
    private StreamedContent content;
    private UploadedFile file;
    public StreamedContent getContent() {
        FacesContext context = FacesContext.getCurrentInstance();

         if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
                return new DefaultStreamedContent();
            }
         else{
             String imageId = context.getExternalContext().getRequestParameterMap().get("id");
            Product product = getProductService().getProductById(Integer.parseInt(imageId));
            return new DefaultStreamedContent(new ByteArrayInputStream(product.getProductImage()));
         }
    }
    public ProductController() {
        bean = new ProductBean();
    }

    public void setContent(StreamedContent content) {
        this.content = content;
    }
    public UploadedFile getFile() {
        return file;
    }

    public void setFile(UploadedFile file) {
        this.file = file;
    }
    public void saveProduct(){
        try{
            Product product = new Product();
            product.setProductImage(getFile().getContents());

            getProductService().saveProduct(product);
            file = null;

        }
        catch(Exception ex){
            ex.printStackTrace();
        }
    }
    public void validateFile(FacesContext ctx,
            UIComponent comp,
            Object value) {
        List<FacesMessage> msgs = new ArrayList<FacesMessage>();
        UploadedFile file = (UploadedFile)value;
        int fileByte = file.getContents().length;
        if(fileByte > 15360){
            msgs.add(new FacesMessage("Too big must be at most 15KB"));
        }
        if (!(file.getContentType().startsWith("image"))) {
            msgs.add(new FacesMessage("not an Image file"));
        }
        if (!msgs.isEmpty()) {
            throw new ValidatorException(msgs);
        }
    }
}

在web.xml中添加以下代码行

<filter>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
</filter-mapping>

关注WEBINF / lib文件夹中的jar文件。

commons-io-X.X  and commons-fileupload-X.X, recommended most recent version.

<击>的公地-IO-2.4,公地-IO-2.4的Javadoc,公地-IO-2.4-源,公地-IO-2.4的测试中,公-IO-2.4 - 测试 - 源,公-fileupload-1.3,公地文件上传-1.3-的Javadoc,公地文件上传-1.3-源,公地文件上传-1.3-测试,公地文件上传-1.3 - 测试 - 源

View.xhtml

<h:form id="ShowProducts">
    <p:dataTable rowsPerPageTemplate="3,6,9" var="products" paginator="true" rows="3" emptyMessage="Catalog is empty" value="#{productController.bean.products}">
        <p:column headerText="Product Name">
            <p:graphicImage width="80" height="80" value="#{productController.content}">
                <f:param name="id" value="#{products.productId}" />
            </p:graphicImage>
            #{products.productName}
        </p:column>
    </p:dataTable>
</h:form>

答案 2 :(得分:0)

我做到了这一点,只需将上传的图像编码为base64,然后通过html <img>标签正常显示即可。

这是我的托管bean:

@ManagedBean
@ViewScoped
public class ImageMB {

private String base64Image;

public void onUploadImage(FileUploadEvent event) {
    String fileName = event.getFile().getFileName();
    //Get file extension.
    String extension = "png";
    int i = fileName.lastIndexOf('.');
    if (i > 0) {
        extension = fileName.substring(i + 1).toLowerCase();
    }

    String encodedImage = java.util.Base64.getEncoder().encodeToString(event.getFile().getContents());
    this.base64Image = String.format("data:image/%s;base64, %s", 
         extension, encodedImage));
}

这是JSF部分:

<p:fileUpload id="imageFileUploader"
              fileUploadListener="#{imageMB.onUploadImage}"
              mode="advanced"    
              multiple="false"
              fileLimit="1"
              allowTypes="/(\.|\/)(gif|jpe?g|png)$/"
              update="@form"/>

<div>
    <img src="#{toolAddEditMB.base64Image}" 
         style="#{toolAddEditMB.base64Image eq null ? 'display: none' : ''}"/>
</div>