9

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

我用两个豆子解决了这个问题;一个视图范围 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>
4

3 回答 3

4

我已经采取了不同的方法。我最初是为了显示上传的图像,但是如果Person还没有创建,那么将它全部保留在客户端似乎是一个更好的主意。我发现了这个问题,并根据选择的答案创建了以下内容:

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

<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;
    }
}
于 2012-09-05T21:43:27.530 回答
4

添加.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>

这是托管 Bean 代码:

@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.

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

查看.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>
于 2013-06-09T15:32:40.623 回答
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>
于 2019-03-13T15:29:32.917 回答