如何使用Ajax检测JSF2.0中的文件上传完成事件

发布于 2024-12-13 12:52:00 字数 3067 浏览 2 评论 0原文

希望你们一切都好。实际上我想将图像文件从系统上传到数据库。但我希望当用户上传文件时,文件不会直接进入数据库,而是在选择文件后。文件可能会保存到某个临时位置,因此当用户单击“保存”按钮时,我会将所有图像移动到数据库。我正在使用 JSF 2.0 和 PrimeFaces。我在某人的博客上找到了代码。代码的作用是上传文件后,将其转换为 byte[] 数组。我将该字节数组保存在列表中,以便通过保存按钮我从列表中获取图像。

这是代码

private StreamedContent image;

public StreamedContent getImage() {
    return image;
}

public void setImage(StreamedContent image) {
    this.image = image;
}

public String imageUpload(FileUploadEvent event) {

    try {

        // Convert file from input stream to bytes
        byte[] byteArray = InputStreamToByte(event.getFile().getInputstream());

        /**
         * Add images to list so we can retrieve them when user click on save button
         */
        boolean add = images.add(new Images(byteArray));


        /**
         * Class.forName("org.postgresql.Driver");
           String url = "jdbc:postgresql://x.x.x.x:5432/MYDB";
           Connection oConnection = DriverManager.getConnection(url, "username", "password");
           System.out.println("Sucessfully connected to Postgres Database");
         *
         * byte[] bytes = bos.toByteArray();
           String sql = "INSERT INTO my_table (byte_array) VALUES (?)";
           statement = oConnection.prepareStatement(sql);
           statement.setBytes(1, bytes);
           statement.executeUpdate();
           System.out.println("Image inserted into database!");
         */

        //byteArray used to store picture into database
        InputStream ist = new ByteArrayInputStream(byteArray);

        /*
         * StreamedContent Object used to show the picture in jsf pages. We need to convert
         * again bytearray to InputStream
         */
        image = new DefaultStreamedContent(ist, "image/jpg");

        FacesMessage msg = new FacesMessage("Succesful picture is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);

        //we dont need to use faces-config to navigate in jsf 2
        return null ;

     } catch (Exception e) {

         FacesMessage msg = new FacesMessage("Exception happen");
         FacesContext.getCurrentInstance().addMessage(null, msg);

         e.printStackTrace();

         return null;

     }

} //end of imageUpload()

这是我的 .html 文件

<h:panelGrid width="30%" columns="3">

    <h:outputText value="Map to upload" />
    <p:fileUpload id="uploadFile"
                  description="Image"
                  update="messages"
                  allowTypes="*.jpg;*.png;*.gif;*.jpeg;"
                  auto="true"
                  fileUploadListener=#{cityDetail.imageUpload} >

        <f:ajax event="????" execute="???" render="uploadedInage" />

    </p:fileUpload>

    <p:graphicImage id="uploadedImage"
                    value="#{cityDetail.image}"


</h:panelGrid>

现在我希望当图像完全上传时,图像也显示到面板网格第三列。为此,我尝试使用 Ajax。但我不知道应该使用什么事件。那么,有人可以告诉我事件名称吗?我还想请求执行,我应该使用“@this”吗? 。还告诉我,我的方法是正确的,将二进制图像保存在列表中,以便当用户单击保存按钮时,我检索所有图像并将它们发送到数据库。另外,对于我的目的来说,使用 Ajax 是正确的想法吗?

谢谢

Hope you all will be fine. Actually i want to upload image files from system to database. But i want that when user upload files then file didn't go to database directly but after selecting files .Files may save to some temporery location, so when user click on save button then i move all the images to database. I am using JSF 2.0 and PrimeFaces. I found code on someone blog. What code does is that after uploading files , it converted it to byte[] array. I save that byte Array in a list so on save button i get images from the List.

Here is the code

private StreamedContent image;

public StreamedContent getImage() {
    return image;
}

public void setImage(StreamedContent image) {
    this.image = image;
}

public String imageUpload(FileUploadEvent event) {

    try {

        // Convert file from input stream to bytes
        byte[] byteArray = InputStreamToByte(event.getFile().getInputstream());

        /**
         * Add images to list so we can retrieve them when user click on save button
         */
        boolean add = images.add(new Images(byteArray));


        /**
         * Class.forName("org.postgresql.Driver");
           String url = "jdbc:postgresql://x.x.x.x:5432/MYDB";
           Connection oConnection = DriverManager.getConnection(url, "username", "password");
           System.out.println("Sucessfully connected to Postgres Database");
         *
         * byte[] bytes = bos.toByteArray();
           String sql = "INSERT INTO my_table (byte_array) VALUES (?)";
           statement = oConnection.prepareStatement(sql);
           statement.setBytes(1, bytes);
           statement.executeUpdate();
           System.out.println("Image inserted into database!");
         */

        //byteArray used to store picture into database
        InputStream ist = new ByteArrayInputStream(byteArray);

        /*
         * StreamedContent Object used to show the picture in jsf pages. We need to convert
         * again bytearray to InputStream
         */
        image = new DefaultStreamedContent(ist, "image/jpg");

        FacesMessage msg = new FacesMessage("Succesful picture is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);

        //we dont need to use faces-config to navigate in jsf 2
        return null ;

     } catch (Exception e) {

         FacesMessage msg = new FacesMessage("Exception happen");
         FacesContext.getCurrentInstance().addMessage(null, msg);

         e.printStackTrace();

         return null;

     }

} //end of imageUpload()

Here is my .html file

<h:panelGrid width="30%" columns="3">

    <h:outputText value="Map to upload" />
    <p:fileUpload id="uploadFile"
                  description="Image"
                  update="messages"
                  allowTypes="*.jpg;*.png;*.gif;*.jpeg;"
                  auto="true"
                  fileUploadListener=#{cityDetail.imageUpload} >

        <f:ajax event="????" execute="???" render="uploadedInage" />

    </p:fileUpload>

    <p:graphicImage id="uploadedImage"
                    value="#{cityDetail.image}"


</h:panelGrid>

Now i want that when image is completely uploaded, the image is also shown to the panel grid 3rd column. For this i am trying to use Ajax. But i don't know what event should i use. So please can any one tell me the event name and also i want to ask for execute i should use "@this" ? .Also tell me that is my approach is right that to save binary image in a List so that when user click on save button then i retreive all the images and send them to database. Also using Ajax is right idea here for my purpose?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柠檬 2024-12-20 12:52:00

所以当用户单击保存按钮时,我将所有图像移动到数据库

然后相应地实现它?

<p:commandButton value="save" action="#{cityDetail.save}" />

public void save() {
    // Move all images to database.
}

so when user click on save button then i move all the images to database

Then just implement that accordingly?

<p:commandButton value="save" action="#{cityDetail.save}" />

with

public void save() {
    // Move all images to database.
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文