在JSF中显示上传的图像

问题描述 投票:9回答:3

我有一个视图范围的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();
    }
}

创建一个人的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>
file-upload jsf-2 primefaces graphicimage
3个回答
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;
    }
}

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>

并在WEB INF / 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 - 测试 - 源,公地文件上传-1.3,公地fileupload- 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>

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>
© www.soinside.com 2019 - 2024. All rights reserved.