1. 程式人生 > >SpringMVC、mybatis查詢資料庫中的二進位制檔案,在前端頁面顯示圖片

SpringMVC、mybatis查詢資料庫中的二進位制檔案,在前端頁面顯示圖片

在做專案的時候,圖片一般是存在單獨的伺服器中,資料庫中只存url地址,這樣做事比較好的,減輕了資料庫的壓力,存取圖片的時候也簡單。然而,也不排除直接將二進位制檔案存到資料庫中的情況,這種做法,無論是存還是取都不方便,也增加了資料庫的壓力,所以儘量避免這種做法。

  • JavaBean
public class CustomerPMProduct {
    private String name;//產品名稱
    private Float weightAu;//含金量
    private String standard;//規格
    private Float remainAmount;//剩餘量
private byte[] thumbnail;//縮圖,這個就是二進位制欄位 public String getStandard() { return standard; } public void setStandard(String standard) { this.standard = standard; } public byte[] getThumbnail() { return thumbnail; } public void setThumbnail(byte[] thumbnail) { this
.thumbnail = thumbnail; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Float getWeightAu() { return weightAu; } public void setWeightAu(Float weightAu) { this.weightAu = weightAu; } public
Float getRemainAmount() { return remainAmount; } public void setRemainAmount(Float remainAmount) { this.remainAmount = remainAmount; } }
  • mapper.java介面
@Component
public interface CustomerPMProductMapper {
    CustomerPMProduct selectPMProduct();
}
  • mapper.xml檔案
<select id="selectPMProduct" resultType="com.yihuisoft.testprojectbiz.entity.CustomerPMProduct">
        SELECT name,
          weight_au weightAu,
          standard,
          REMAIN_AMOUNT remainAmount,
          THUMBNAIL01 thumbnail
        FROM
          (SELECT name,
            weight_au,
            standard,
            REMAIN_AMOUNT ,
            THUMBNAIL01
          FROM PM_PRODUCT
          WHERE exp_yield IS NOT NULL
          ORDER BY exp_yield DESC
          )
        WHERE rownum=1
    </select>
  • service
 public OutDTO selectPMProduct(InDTO inDTO){
        OutDTO outDTO = new OutDTO();
        CustomerPMProduct pmProduct = wealthSuccessionMapper.selectPMProduct();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data",pmProduct);
        outDTO.setData(jsonObject);
        return outDTO;
    }
  • 前端顯示
  • image標籤
<img id="img1" src="" height="128px" width="200px">
  • js
document.getElementById("img1").src = "data:image/png;base64,"+this.pmProduct.thumbnail;