15

我的模型存储图像用文件名(作为字符串)和数据(作为字节数组)描述。我使用 Hibernate,这是我的模型:

@Entity
public class Image {

    private Long id;
    private String name;
    private byte[] data;

    @Id
    @GeneratedValue
    @Column(name = "IMAGE_ID")
    public Long getId() {
        return id;
    }

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

    @Column(nullable = false, length = 100)
    public String getName() {
        return name;
    }

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

    @Lob
    @Column(nullable = false)
    public byte[] getData() {
        return data;
    }

    public void setData(byte[] data) {
        this.data = data;
    }
}

但我想在网站上显示我存储的图像,例如:

<img src="${image.data}" alt="car_image"/>

我怎么能那样做?

我应该编写服务图像请求的控制器吗?

任何代码示例?


更新

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass"
        value="org.springframework.web.servlet.view.tiles2.TilesView" />
</bean>

<bean id="tilesConfigurer"
    class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
    <property name="definitions">
        <list>
            <value>/WEB-INF/configs/tiles.xml</value>
        </list>
    </property>
</bean>
4

6 回答 6

33

你不能这样做。您的图像必须通过普通 URL 以某种方式公开。在 Spring MVC 中创建一个控制器,该控制器在特定 URL 下返回图像(原始数据):

@RequestMapping(value = "/imageController/{imageId}")
@ResponseBody
public byte[] helloWorld(@PathVariable long imageId)  {
  Image image = //obtain Image instance by id somehow from DAO/Hibernate
  return image.getData();
}

现在在您的 JSP 页面中使用它。这就是 HTTP/HTML 的工作方式:

<img src="/yourApp/imageController/42.png" alt="car_image"/>

在 3.1 之前的 Spring MVC 中,您可能需要在控制器端进行更多编码。但原理是一样的。

于 2012-04-08T20:51:54.477 回答
18
File file = new File("home/user/test.jpg");
FileInputStream fis=new FileInputStream(file);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
int b;
byte[] buffer = new byte[1024];
while((b=fis.read(buffer))!=-1){
   bos.write(buffer,0,b);
}
byte[] fileBytes=bos.toByteArray();
fis.close();
bos.close();


byte[] encoded=Base64.encodeBase64(fileBytes);
String encodedString = new String(encoded);

ModelMap map = new ModelMap();
map.put("image", encodedString);

现在在您的 JSP 页面中使用它,如下所示

<img src="data:image/jpeg;base64,${image}" alt="..." width="200" height="200">`
于 2013-12-10T02:08:45.223 回答
6

您可能需要查看这篇文章。我和你有类似的问题,解决方案是将字节数组转换为字符串并在 img 标签中设置,如下所示,

 <img src="data:image/jpg;base64,<c:out value='${bean.imageByteArrayString}'/>" />
于 2012-05-09T06:26:55.367 回答
4

几天来我一直在寻找正确的答案,所以我会为我写一个好的答案:

我的图像已经保存在数据库中:

@Entity
@Table(name="PRODUCT")
public class Product {

 @Lob
 @Column(name="IMG")
 private byte[] img;

// setters getters etc
}

现在在我的课堂上,例如 ShowPicture,我必须阅读它:

String encodedImage = Base64.encode(product.getImg());
//setters and getters encodedImage

然后我的jsp页面:

<img src='data:image/jpg;base64,<s:property value='encodedImage'/>' alt="my image" />

就那么简单 !:)

于 2014-07-24T07:06:43.100 回答
1

也许已经晚了,但我在这里留下了一些对我有用的东西,也许有人可以帮忙。

我也在使用 Spring MVC 和 Hibernate

模型(实体类)中创建一个 String 类型的变量,以使用 Base64 将类型 byte 转换为 String。

我为我拥有的带有各自国旗的国家表做了这个,我想要在一个表格中列出所有国家和国家的国旗。

模型(实体)

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;

@Entity
@Table(name = "country")
public class Country implements java.io.Serializable {

private int id;
private String name;
private byte[] flag;
private String base64; //Variable to store the conversion of a data byte type to String

@Transient //Annotation so it does not persist in the database
public String getBase64() {
    //Convert the data type byte to String, store it in the variable and return it
    return this.base64 = Base64.encode(this.flag); 
}

public void setBase64(String base64) {
    this.base64 = base64;
}

public Country() {
}

public Country(int id, String name, byte[] flag, String base64) {
    this.id = id;
    this.name = name;
    this.flag = this.flag
    this.base64 = this.base64;
}

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public int getId() {
    return this.id;
}

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

@Column(name = "name")
public String getName() {
    return this.name;
}

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

@Column(name = "flag")
public byte[] getFlag() {
    return this.flag;
}

public void setFlag(byte[] flag) {
    this.flag = flag;
}

}

Repository - Implements 是一个接口 - AbstractDao 是一个类 Abstract import org.springframework.stereotype.Repository; 导入应用程序.model.Country;导入 application.repository.dao.AbstractDao;导入 application.repository.dao.CountryDao;导入 org.hibernate.Criteria;

@Repository("countryDao")
public class CountryDaoImpl extends AbstractDao<Integer, Country> implements CountryDao {

@Override
@SuppressWarnings("unchecked")
public List<Country> listCountries() {
    Criteria criteria = createEntityCriteria(); //Country.class
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    List<Country> listCountries = criteria.list();
    return listCountries;
}

}

服务 - 实现是一个接口

import application.model.Country;
import application.repository.dao.CountryDao;
import application.service.dao.CountryService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("countryService")
public class CountryServiceImpl implements CountryService {

@Autowired
private CountryDao countryDao;

@Override
@Transactional(readOnly = true)
public List<Country> listCountries() {
    return countryDao.listCountries();
}
}

控制器

import application.model.Country;
import application.service.dao.CountryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value = "/countries")
public class CountryController {

@Autowired
private CountryService countryService;

@RequestMapping(value = "/list", method = RequestMethod.GET)
public String ListCountries(Model model) {
    model.addAttribute("listcont", countryService.listCountry());
    return "countries/countries"; //view
}

}

查看 - countries/countries.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <body>
    <h3>List Countries</h3>
    <table>
      <thead>
        <tr>
          <th>Name</th>
          <th>Flag</th>
        </tr>
      </thead>
      <tbody>
        <c:forEach items="${listcont}" var="country">
         <tr>
          <td>${country.name}</td>
          <td><img src="data:image/png;base64,${country.base64}" /></
         </tr>
        </c:forEach>
      </tbody>
    </table> 
  </body>
</html>
于 2016-12-08T16:17:22.513 回答
0
byte[] img = yourImgEntity.getData();
response.setContentType("image/*"); 
response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache");
//spring-core's FileCopyUtils
FileCopyUtils.copy(img, response.getOutputStream());

// or just use codes below instead of FileCopyUtils
//response.getOutputStream().write(img);
//response.getOutputStream().flush();
//response.getOutputStream().close();
于 2012-04-09T03:17:54.013 回答