JSF和JAVA-上传图像后显示图像

时间:2020-08-26 15:20:41

标签: jsf file-upload

我只是为实验制作了一个xhtml文件和一个bean文件。我要上传图片,将其保存在“资源->图片”下并显示。这是行不通的。它显示了一个X,就这样。你能弄清楚出什么问题了吗?

我要重复:我需要显示它。并且不仅保存它! 并且不使用任何PrimeFaces 。这是一个限制

此代码将上载图像并将其保存为虚拟名称“ bla.jpg”的本地驱动器。按下命令链接后,它应该保存图像并更改属性“ nameImage”。通过使用ajax,应该通过将'name'属性更改为nameImage属性来显示图像。

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        <h:form enctype="multipart/form-data">
            <h:outputLabel value="Main Image: " for="main_image"/>
            <h:inputFile id="main_image_file" value="#{animal2.mainImage}"  >   
            </h:inputFile>
            <h:commandLink value ="upload" >
                <f:ajax  execute="main_image_file" render="imageToDisplay"/>
            </h:commandLink>
            <h:graphicImage id = "imageToDisplay" library="images" name="#{animal2.nameMain}"/>
        </h:form>
     
    </h:body>
</html>

@Named(value = "animal2")
@SessionScoped
public class Animal2 implements Serializable {
    private Part mainImage;
    private String nameMain;
    
    public Animal2()
    {
        mainImage = null;
        nameMain = null;
    }
    private void saveImageDisc(Part imagePart, String filename)
    {
        File file = null;
        try {     
            //absolute path
            file = new File("C:\\Users\\ozhar\\Desktop\\workspace java\\"
                    + "animals\\web\\resources\\images\\"+filename);
            file.createNewFile();
            
            OutputStream out = new FileOutputStream(file);
            InputStream in = imagePart.getInputStream();
            
            //magic number
            byte[] buffer = new byte[1024];
            int length;

            while ((length = in.read(buffer)) > 0)
            {
                out.write(buffer,0,length);
            }
            in.close();
            out.close();
        } catch (IOException e) {
            
        }
    }
    public Part getMainImage() {
        return mainImage;
    }

    public void setMainImage(Part mainImage) {
        this.mainImage = mainImage;
        nameMain = "bla.jpg";
        saveImageDisc(mainImage, "bla.jpg");
    }

    public String getNameMain() {
        return nameMain;
    }

    public void setNameMain(String nameMain) {
        this.nameMain = nameMain;
    }
}

0 个答案:

没有答案