简体   繁体   中英

How to display byte[] image in JSP using Struts2

I am trying to display a byte array image in a JSP using Struts2. First of all, the image was uploaded as follows:

saveImage.jsp

<s:form action="saveImage" enctype="multipart/form-data" method="POST">
   <s:file name="file"/>
</s:form>

struts.xml

<action name="saveImage" class="com.actions.ImageAction" method="save">
        <result name="success" type="redirect">listImages</result>
</action>
<action name="listImages" class="com.actions.ImageAction" method="list">
        <result name="success">listImages.jsp</result>
</action>

ImageAction.class

public class ImageAction extends ActionSupport  implements ModelDriven<Image> {

    private Image = new Image();
    private File file;
    private List<Image> imageList = new ArrayList<>();

    public Image getImage() {
       return image;
    }
    public void setImage(Image image) {
       this.image = image;
    } 
    public File getFile() {
            return file;
    } 
    public List<Image> getImageList() {
        return imageList;
    }

    public void setImageList(List<Image> imageList) {
        this.imageList = imageList;
    }

Configuration config = new Configuration().configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);

Session session = null;

    @SkipValidation
    public String save() {
        try {
             session = sessionFactory.openSession();
             session.beginTransaction();

            byte[] byteFile = new byte[(int) file.length()];
                try {
                    FileInputStream fs = new FileInputStream(file);
                    fs.read(byteFile);
                    fs.close();
                } catch (Exception e) {}
            image.setImageData(byteFile);

             session.saveOrUpdate(image);
             session.getTransaction().commit()
        } catch (Exception e) {
            session.getTransaction().rollback();
        } finally {
            session.close();
        }
        return SUCCESS;
    }

    @SkipValidation
    public String list() {
        try {
            session = sessionFactory.openSession();
            session.beginTransaction();
            imageList = session.createQuery("from Image").list();
            session.getTransaction().commit();
        } catch (Exception e) {
            session.getTransaction().rollback();
        } finally {
            session.close();
        }
        return SUCCESS;
    }

@Override
public Image getModel() {
    return image;
}

}

The Image object has a byte[] imageData property and is saved to DB using Hibernate. Now, after successfully saving the image byte array to DB, Struts calls the listImages action that shows in a listImages.jsp the list of existing images in DB.

listImages.jsp

     <s:if test="imageList.size() > 0">
       <ul>
        <s:iterator value="imageList">
         <li><s:property value="imageData" /></li>
        </s:iterator>
       </ul>
     </s:if>

Using this "property" tag only shows me some string associated with the image byte array, such as "[B@2eeb2d23". My question is: how do I display a clickable thumbnail or even a URL instead of that string? And then, when I click the thumbnail or URL, to display the full size image. I tried many different approaches but none of them worked. Maybe it's something I do wrong at uploading the file, or saving it on DB... please provide a working solution. Thanks.

In HTML, images and other resources are not part of the HTML page, but are referenced by it.

So, your HTML will need to have <img src="[URL TO THE IMAGE]"/> and your JSP will be something like

<s:iterator value="imageList">
  <img src="[DOWNLOAD_URL]?id=${imageId}"/>
</s:iterator>

where DOWNLOAD_URL will point to a HttpServlet that serves the image data based in its id.

Found a partial workaround, using this solution: http://java.dzone.com/articles/struts2-tutorial-part-67

So basically I'm not saving the image's byte array to DB anymore. When uploading the image through struts, I only save the image's filename into DB and then I make a copy of the image (since the temporary image will be deleted shortly after the upload action is ended) and save the copy on the server as explained in the provided tutorial above. Then, for displaying a certain image, I query it's name from DB and then retrieve it from the location where I copied it the first time, when I uploaded it on the server. Thanks SJuan76 for the hint.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM