数据库实体类:
package com.easy.kotlin.picturecrawler.entity
import java.util.*
import javax.persistence.*
@Entity
@Table(indexes = arrayOf(
Index(name = "idx_url", unique = true, columnList = "url"),
Index(name = "idx_category", unique = false, columnList = "category")))
class Image {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long = -1
@Version
var version: Int = 0
@Column(length = 255, unique = true, nullable = false)
var category: String = ""
var isFavorite: Int = 0
@Column(length = 255, unique = true, nullable = false)
var url: String = ""
var gmtCreated: Date = Date()
var gmtModified: Date = Date()
var isDeleted: Int = 0 //1 Yes 0 No
var deletedDate: Date = Date()
@Lob
var imageBlob: ByteArray = byteArrayOf()
/* 0-Baidu 1-Gank */
var sourceType: Int = 0
override fun toString(): String {
return "Image(id=$id, version=$version, category='$category', isFavorite=$isFavorite, url='$url', gmtCreated=$gmtCreated, gmtModified=$gmtModified, isDeleted=$isDeleted, deletedDate=$deletedDate)"
}
}
其中的 @Lob var imageBlob: ByteArray = byteArrayOf() 这个字段存储图片的 Base64内容。
存库代码
val Image = Image()
Image.category = "干货集中营福利"
Image.url = url
Image.sourceType = 1
Image.imageBlob = getByteArray(url)
logger.info("Image = ${Image}")
imageRepository.save(Image)
其中的getByteArray(url) 函数:
private fun getByteArray(url: String): ByteArray {
val urlObj = URL(url)
return urlObj.readBytes()
}
前端 html 展示图片代码:
{
title: '图片',
field: 'imageBlob',
align: 'center',
valign: 'middle',
formatter: function (value, row, index) {
// var html = "<img onclick=downloadImage('" + value + "') width='100%' src='" + value + "'>"
var html = '<img onclick="downBase64Image(this.src)" width="100%" src="data:image/jpg;base64,' + value + '"/>'
return html
}
}
点击下载 js :
function downloadImage(src) {
var $a = $("<a></a>").attr("href", src).attr("download", "sotu.png");
$a[0].click();
}
function downBase64Image(url) {
var blob = base64Img2Blob(url);
url = window.URL.createObjectURL(blob);
var $a = $("<a></a>").attr("href", url).attr("download", "sotu.png");
$a[0].click();
}
function base64Img2Blob(code) {
var parts = code.split(';base64,');
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {type: contentType});
}
或者:
function downloadFile(fileName, content) {
var aLink = document.createElement('a');
var blob = base64Img2Blob(content); //new Blob([content]);
var evt = document.createEvent("HTMLEvents");
evt.initEvent("click", false, false);//initEvent 不加后两个参数在FF下会报错
aLink.download = fileName;
aLink.href = URL.createObjectURL(blob);
aLink.dispatchEvent(evt);
}