本文介绍了休眠 - 如何从数据库中检索图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以某种方式设法在数据库中存储图像,但现在我想再次检索/显示图像。我只是不知道如何。基本上我的问题是如果我在我的ImageDao中缺少任何进一步的方法或者jsp中的配置应该如何。



有我的图像类:

  package de.hdu。 pms.model; 

import java.sql.Blob;
import java.util.Date;
import java.util.Set;

import javax.persistence。*;


@Entity
@Table(name =tbl_image)
public class Image {
@Id
@GeneratedValue
@Column(name =image_id)
private Integer id;


私人字符串名称;


私人字符串描述;


私人字符串文件名;

@Column(name =content,columnDefinition =mediumblob)
@Lob
私人Blob内容;


私人字符串contentType;

私人创建日期;

public Integer getId(){
return id;
}

public void setId(Integer id){
this.id = id;
}

public String getName(){
return name;
}

public void setName(String name){
this.name = name;
}

public String getDescription(){
return description;
}

public void setDescription(String description){
this.description = description;
}

public String getFilename(){
return filename;
}

public void setFilename(String filename){
this.filename = filename;
}

public Blob getContent(){
return content;
}

public void setContent(Blob content){
this.content = content;
}

public String getContentType(){
return contentType;
}

public void setContentType(String contentType){
this.contentType = contentType;
}

public Date getCreated(){
return created;
}

public void setCreated(创建日期){
this.created = created;
}



}

ImageDao

  package de.hdu.pms.dao; 

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;



导入de.hdu.pms.model.Image;

$ b public class ImageDao extends HibernateDaoSupport {

$ b public void save(Image image){
HibernateTemplate template = getHibernateTemplate();
template.saveOrUpdate(image);
}

@SuppressWarnings(unchecked)
public List< Image> list(){
HibernateTemplate template = getHibernateTemplate();
// evtl ersetzen durch hibernate模板
@SuppressWarnings(rawtypes)
List images = template.loadAll(Image.class);
返回图片;
}

public Image get(Integer id){
HibernateTemplate template = getHibernateTemplate();
返回template.get(Image.class,id);



$ b @Transactional
// hibernate
public void remove(Integer id){
HibernateTemplate template = getHibernateTemplate ();

Image image = template.get(Image.class,id);
template.delete(image);
}

}

ImageController:

  package de.hdu.pms.ctrl; 

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

导入org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
导入org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;



导入de.hdu.pms.dao.CocktailDao;
import de.hdu.pms.dao.ImageDao;
导入de.hdu.pms.model.Image;

@Controller
public class ImageController {

@Autowired
ImageDao imageDao;

public ImageDao getImageDao(){
return imageDao;
}

public void setImageDao(ImageDao imageDao){
this.imageDao = imageDao;
}
// aus dem教程

@RequestMapping(/ EditImage.html)
public String index(Map< String,Object> map){
尝试{
map.put(image,new Image());
map.put(imageList,imageDao.list());
} catch(Exception e){
e.printStackTrace();
}

returnedit-image;
}

// aus dem教程




@RequestMapping(value =/SaveImage.html,方法= RequestMethod.POST)
public String save(
@ModelAttribute(image)Image image,
@RequestParam(file)MultipartFile文件){


System.out.println(Name:+ image.getName());
System.out.println(Desc:+ image.getDescription());
System.out.println(File:+ file.getName());
System.out.println(ContentType:+ file.getContentType());

尝试{
Blob blob = Hibernate.createBlob(file.getInputStream());

image.setFilename(file.getOriginalFilename());
image.setContent(blob);
image.setContentType(file.getContentType());
} catch(IOException e){
e.printStackTrace();
}

尝试{
imageDao.save(image);
} catch(Exception e){
e.printStackTrace();
}

返回redirect:/AlleImages.html;

$ b @RequestMapping(/ download / {imageId})
public String download(@PathVariable(imageId)
整型imageId,HttpServletResponse响应) {

Image img = imageDao.get(imageId);
try {
response.setHeader(Content-Disposition,inline; filename = \+ img.getFilename()+\);
OutputStream out = response.getOutputStream();
response.setContentType(img.getContentType());
IOUtils.copy(img.getContent()。getBinaryStream(),out);
out.flush();
out.close();

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


返回null;
}

@RequestMapping(value =/ AlleImages.html,method = RequestMethod.GET)
public ModelAndView list(){
ModelAndView mv = new ModelAndView ();
mv.addObject(title,Images);
mv.addObject(message,Alle gespeicherten Images);
mv.addObject(image,imageDao.list());
// furr jsp bedingung
mv.addObject(edit,true);
mv.setViewName(list-image);
return mv;
}


}

最后一个

 < h3>图片列表< h3>图片列表< / H3> 
< c:if test =$ {!empty imageList}>
< table class =data>
< tr>
< th>名称< / th>
< th>说明< / th>
th& nbsp;< / th>
< / tr>
< c:forEach items =$ {imageList}var =image>
< tr>
< td width =100px> $ {image.name}< / td>
< td width =250px> $ {image.description}< / td>
< td width =250px> $ {image.content}< / td>


< / tr>
< / c:forEach>

如果有人能帮助我,我真的很感激。谢谢

解决方案

问题在于您了解HTTP和HTML如何工作。当网页包含图像时,HTML不包含图像的内容。它包含的是一个 img 标记,其src属性包含此图像的URL:

 < img src =/ the / path / of / the / image.jpg/> 

浏览器发送第一个获取HTML页面的请求。然后它解析HTML,看到 img 标记,并向图像的URL发送第二个请求以获取其内容(字节)并显示它。



您的代码尝试生成一个包含blob的HTML页面(实际上,直接在页面上调用blob上的toString()的结果):

 < td width =250px> $ {image.content}< / td> 

这是不正确的。

需要生成一个图片标签,其src属性包含动作的URL,它将从数据库中获取图片字节并将其发送到浏览器,即 img 标记指向到下载动作:

 < td width =250px>< img src =< c:url值= '/下载/ $ {image.id}'/>中/>< / TD> 


I somehow managed to store an image in the database, but now I want to retrieve/display the image again. I just do not know how. Basically my question is if I am missing any further method in my ImageDao or how the configuration in the jsp should look like.

There is my Image Class:

package de.hdu.pms.model;

import java.sql.Blob;
import java.util.Date;
import java.util.Set;

import javax.persistence.*;


@Entity
@Table(name="tbl_image")
public class Image {
     @Id
     @GeneratedValue
     @Column(name="image_id")
      private Integer id;


        private String name;


        private String description;


        private String filename;

        @Column(name="content", columnDefinition="mediumblob")
        @Lob
        private Blob content;


        private String contentType;

        private Date created;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public String getFilename() {
            return filename;
        }

        public void setFilename(String filename) {
            this.filename = filename;
        }

        public Blob getContent() {
            return content;
        }

        public void setContent(Blob content) {
            this.content = content;
        }

        public String getContentType() {
            return contentType;
        }

        public void setContentType(String contentType) {
            this.contentType = contentType;
        }

        public Date getCreated() {
            return created;
        }

        public void setCreated(Date created) {
            this.created = created;
        }



}

ImageDao

package de.hdu.pms.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;



import de.hdu.pms.model.Image;


public class ImageDao extends HibernateDaoSupport {


        public void save(Image image) {
            HibernateTemplate template = getHibernateTemplate();
            template.saveOrUpdate(image);
        }

        @SuppressWarnings("unchecked")
        public List<Image> list() {
           HibernateTemplate template = getHibernateTemplate();
            //evtl ersetzen durch hibernate template
           @SuppressWarnings("rawtypes")
           List images=template.loadAll(Image.class);
            return images;
        }

        public Image get(Integer id) {
            HibernateTemplate template = getHibernateTemplate();
            return template.get(Image.class, id);
        }



     @Transactional
     //hibernate
        public void remove(Integer id) {
          HibernateTemplate template = getHibernateTemplate();

            Image image = template.get(Image.class, id);
             template.delete(image);
        }

}

ImageController:

package de.hdu.pms.ctrl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;



import de.hdu.pms.dao.CocktailDao;
import de.hdu.pms.dao.ImageDao;
import de.hdu.pms.model.Image;

@Controller
public class ImageController {

    @Autowired
    private ImageDao imageDao;

    public ImageDao getImageDao(){
        return imageDao;
    }

    public void setImageDao(ImageDao imageDao){
        this.imageDao = imageDao;
    }
    //aus dem Tutorial

     @RequestMapping("/EditImage.html")
     public String index(Map<String, Object> map) {
            try {
                map.put("image", new Image());
                map.put("imageList", imageDao.list());
            }catch(Exception e) {
                e.printStackTrace();
            }

            return "edit-image";
        }

        //aus dem Tutorial




     @RequestMapping(value = "/SaveImage.html", method = RequestMethod.POST)
        public String save(
                @ModelAttribute("image") Image image,
                @RequestParam("file") MultipartFile file) {


            System.out.println("Name:" + image.getName());
            System.out.println("Desc:" + image.getDescription());
            System.out.println("File:" + file.getName());
            System.out.println("ContentType:" + file.getContentType());

            try {
                Blob blob = Hibernate.createBlob(file.getInputStream());

                image.setFilename(file.getOriginalFilename());
                image.setContent(blob);
                image.setContentType(file.getContentType());
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                imageDao.save(image);
            } catch(Exception e) {
                e.printStackTrace();
            }

            return "redirect:/AlleImages.html";
        }

        @RequestMapping("/download/{imageId}")
        public String download(@PathVariable("imageId")
                Integer imageId, HttpServletResponse response) {

            Image img = imageDao.get(imageId);
            try {
                response.setHeader("Content-Disposition", "inline;filename=\"" +img.getFilename()+ "\"");
                OutputStream out = response.getOutputStream();
                response.setContentType(img.getContentType());
                IOUtils.copy(img.getContent().getBinaryStream(), out);
                out.flush();
                out.close();

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


            return null;
        }

        @RequestMapping(value="/AlleImages.html", method=RequestMethod.GET)
        public ModelAndView list(){
            ModelAndView mv = new ModelAndView();
            mv.addObject("title", "Images");
            mv.addObject("message", "Alle gespeicherten Images");
            mv.addObject("image", imageDao.list());
            // für die jsp bedingung
            mv.addObject("edit",true);
            mv.setViewName("list-image");
            return mv;
        }


}

And finally a code snippet of my jsp where I wanted to "access" the image - but I failed :

                                                    <h3>Image List</h3>
                                                    <c:if  test="${!empty imageList}">
                                                    <table class="data">
                                                    <tr>
                                                        <th>Name</th>
                                                        <th>Description</th>
                                                        <th>&nbsp;</th>
                                                    </tr>
                                                    <c:forEach items="${imageList}" var="image">
                                                        <tr>
                                                            <td width="100px">${image.name}</td>
                                                            <td width="250px">${image.description}</td>
                                                            <td width="250px">${image.content}</td>


                                                        </tr>
                                                    </c:forEach>

I really would appreciate if someone could help me. Thanks

解决方案

The problem is with your understanding of how HTTP and HTML work. When a web page contains an image, the HTML doesn't containg the content of the image. All it contains is an img tag, with an src attribute containing the URL of this image:

<img src="/the/path/of/the/image.jpg"/>

The browser sends a first request to get the HTML page. Then it parses the HTML, sees the img tag, and sends a second request to the URL of the image to get its content (bytes) and display it.

Your code tries to generate an HTML page containing the blob (in fact, the result of calling toString() on the blob) directly in the page:

<td width="250px">${image.content}</td>

That is incorrect.

What you need to generate is an image tag whose src attribute contains the URL of the action which will get the image bytes from the database and send them to the browser, i.e. an img tag pointing to the download action:

<td width="250px"><img src="<c:url value='/download/${image.id}'/>"/></td>

这篇关于休眠 - 如何从数据库中检索图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 18:38