小编典典

使用Struts 2和Hibernate在jsp页面中显示Blob(图像)

hibernate

我设法将图像以Blob的形式存储在mysql数据库中。(我也在使用hibernate模式)现在我试图加载该图像并将其发送到jsp页面上,以便用户可以查看该图像。

这是我的struts 2动作课

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Blob;
import org.hibernate.Hibernate;

import domain.post.image.Image;



public class FileUploadAction {

  private File file;

  @SuppressWarnings("deprecation")
  public String execute() {

      try {
          System.out.println(file.getPath());
          Image image = new Image();
          FileInputStream fi = new FileInputStream(file);

          Blob blob = Hibernate.createBlob(fi);
          image.setImage(blob);
          image.save();

      } catch (FileNotFoundException e) {

          e.printStackTrace();
      } catch (IOException e) {

          e.printStackTrace();
      }
      return "success";
  }

  public File getFile() {
      return file;
  }

  public void setFile(File file) {
      this.file = file;
  }

这是我的图片课

public class Image extends AbsDBObject<Object> {


  private static final long serialVersionUID = 1L;
  private static Logger logger = Logger.getLogger(Image.class);
  private Blob image;
  private String description;

//Getters and Setters

}

您能告诉我我应该在动作类,jsp页面和struts.xml中放置什么以显示存储的图像吗?


阅读 463

收藏
2020-06-20

共1个答案

小编典典

最终,我为未来的Google员工解决了这一问题:

将此行添加到jsp,

 <img src="<s:url value="YourImageShowAction" />" border="0"
 width="100" height="100">

这是ShowImageActionclass:请注意execute方法是无效的,因此没有重定向

import java.io.IOException;
import java.io.OutputStream;
import java.sql.SQLException;

import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.raysep.maxlist.domain.post.image.Image;

public class ShowImageAction {

  private static byte[] itemImage;

  public static void execute() {

      try {

          Image slika = Image.fetchOne();

          HttpServletResponse response =

ServletActionContext.getResponse();
response.reset();
response.setContentType(“multipart/form-data”);

          itemImage = slika.getImage().getBytes(1,(int)

slika.getImage().length());

          OutputStream out = response.getOutputStream();
          out.write(itemImage);
          out.flush();
          out.close();

      } catch (SQLException e) {
          e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
      }


  }

  public byte[] getItemImage() {
      return itemImage;
  }

  public void setItemImage(byte[] itemImage) {
      this.itemImage = itemImage;
  }


}
2020-06-20