Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
File upload 在JSF中显示上传的图像_File Upload_Jsf 2_Primefaces_Graphicimage - Fatal编程技术网

File upload 在JSF中显示上传的图像

File upload 在JSF中显示上传的图像,file-upload,jsf-2,primefaces,graphicimage,File Upload,Jsf 2,Primefaces,Graphicimage,我有一个视图范围的bean,在这里我创建了一个人。一个人可以有一张照片。此图片上载到创建该人的同一页面。图片未存储在数据库或磁盘中(因为人物尚未创建)。bean必须是视图范围的,因为可以在其他地方创建人员,并且这使用相同的bean。如果bean是会话范围的,并且用户上载了一张图片但没有保存此人,那么在用户下次尝试创建此人时,将显示该图片 我用两颗豆子解决了这个问题;一个视图范围的bean用于创建person,一个会话范围的bean用于上传图片并将图片作为流获取。但是,这会导致上述问题 我怎样才能

我有一个视图范围的bean,在这里我创建了一个人。一个人可以有一张照片。此图片上载到创建该人的同一页面。图片未存储在数据库或磁盘中(因为人物尚未创建)。bean必须是视图范围的,因为可以在其他地方创建人员,并且这使用相同的bean。如果bean是会话范围的,并且用户上载了一张图片但没有保存此人,那么在用户下次尝试创建此人时,将显示该图片

我用两颗豆子解决了这个问题;一个视图范围的bean用于创建person,一个会话范围的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>

我选择了另一种方法。我最初打算显示一个上传的图像,但是如果没有创建
,将其保存在客户端似乎是一个更好的主意。我根据选择的答案找到并创建了以下内容:

如果浏览器为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" />
uploadedPicture
属性现在是一个简单的属性:

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

    public UploadedFile getUploadedPicture()
    {
        return uploadedPicture;
    }

    public void setUploadedPicture(UploadedFile uploadedPicture)
    {
        this.uploadedPicture = uploadedPicture;
    }
}
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>
commons-io-2.4、commons-io-2.4-javadoc、commons-io-2.4-sources、commons-io-2.4-tests、commons-io-2.4-test-sources、commons-fileupload-1.3、commons-fileupload-1.3-javadoc、commons-fileupload-1.3-sources、commons-fileupload-1.3-tests、commons-fileupload-1.3-test-sources

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>

#{products.productName}

我只需将上传的图像编码到base64,然后通过html正常显示即可
尽量缩短示例。里面有很多不必要的代码。有趣的是,您要求在JSF中提供一个示例,并以一些“Javascript/JQuery魔术”结束。另外,你对另一个答案的评论不仅仅是必要的,因为他的例子非常好。有很多JSF方法可以很好地完成您的任务,这里不需要包含JS。你能同时编辑你的问题或答案吗?问题和答案不匹配。答案解决了我的问题,那么它们如何不匹配呢?我还要声明,这个问题的日期是2012年7月16日,那是两年多前的事了。我可以有把握地说,这个问题与我无关。如果我的答案有问题,你可以编辑它。;-)
<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>
@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);
        }
    }
}
<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>
commons-io-X.X  and commons-fileupload-X.X, recommended most recent version.
<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>
@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));
}
<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>