详解如何使用beego orm在postgres中存储图片
作者:中等生 发布时间:2024-04-25 15:14:46
Postgres如何存储文件
postgres提供了两种不同的方式存储二进制,要么是使用bytea类型直接存储二进制,要么就是使用postgres的LargeObject功能;决定使用哪中方式更加适合你,就需要了解这两种存储方式有哪些限制
bytea类型
bytea类型在单列中虽然可以支持1GB的容量,但是还是不建议使用bytea去储存比较大的对象,因为它会占用大量的内存
下面通过一个例子来说明,假如现在要在一个表中存储图片名和该图片的数据,创建表如下:
CREATE TABLE images (imgname text, img bytea);
在表中插入一张图片:
File file = new File("myimage.gif");
FileInputStream fis = new FileInputStream(file);
PreparedStatement ps = conn.prepareStatement("INSERT INTO images VALUES (?, ?)");
ps.setString(1, file.getName());
ps.setBinaryStream(2, fis, file.length());
ps.executeUpdate();
ps.close();
fis.close();
上面的setBinaryStream就会将图片内容设置到img字段上面,也可以使用setBytes()直接设置图片的内容
接下来,从表中取出图片,代码如下:
PreparedStatement ps = con.prepareStatement("SELECT img FROM images WHERE imgname = ?");
ps.setString(1, "myimage.gif");
ResultSet rs = ps.executeQuery();
if (rs != null) {
while (rs.next()) {
byte[] imgBytes = rs.getBytes(1);
// use the data in some way here
}
rs.close();
}
ps.close();
Large Object
Large Object就可以存储大文件,存储的方式是在单独的一张表中存储大文件,然后通过oid在当前表中进行引用;下面通过一个例子来解释:
CREATE TABLE imageslo (imgname text, imgoid oid);
首先是创建一张表,该表中第二个字段类型为oid,之后就是通过该字段引用大文件对象;下面我们在表中插入一张图片:
// All LargeObject API calls must be within a transaction block
conn.setAutoCommit(false);
// Get the Large Object Manager to perform operations with
LargeObjectManager lobj = ((org.postgresql.PGConnection)conn).getLargeObjectAPI();
// Create a new large object
int oid = lobj.create(LargeObjectManager.READ | LargeObjectManager.WRITE);
// Open the large object for writing
LargeObject obj = lobj.open(oid, LargeObjectManager.WRITE);
// Now open the file
File file = new File("myimage.gif");
FileInputStream fis = new FileInputStream(file);
// Copy the data from the file to the large object
byte buf[] = new byte[2048];
int s, tl = 0;
while ((s = fis.read(buf, 0, 2048)) > 0) {
obj.write(buf, 0, s);
tl += s;
}
// Close the large object
obj.close();
// Now insert the row into imageslo
PreparedStatement ps = conn.prepareStatement("INSERT INTO imageslo VALUES (?, ?)");
ps.setString(1, file.getName());
ps.setInt(2, oid);
ps.executeUpdate();
ps.close();
fis.close();
在代码中需要使用lobp.open打开一个大文件,然后将图片的内容写入这个对象当中;下面从大文件对象中读取这个图片:
// All LargeObject API calls must be within a transaction block
conn.setAutoCommit(false);
// Get the Large Object Manager to perform operations with
LargeObjectManager lobj = ((org.postgresql.PGConnection)conn).getLargeObjectAPI();
PreparedStatement ps = con.prepareStatement("SELECT imgoid FROM imageslo WHERE imgname = ?");
ps.setString(1, "myimage.gif");
ResultSet rs = ps.executeQuery();
if (rs != null) {
while (rs.next()) {
// Open the large object for reading
int oid = rs.getInt(1);
LargeObject obj = lobj.open(oid, LargeObjectManager.READ);
// Read the data
byte buf[] = new byte[obj.size()];
obj.read(buf, 0, obj.size());
// Do something with the data read here
// Close the object
obj.close();
}
rs.close();
}
ps.close();
需要注意的是,对于Large Object的操作都需要放在一个事务(Transaction)当中;如果要删除大文件所在行,在删除这行之后,还需要再执行删除大文件的操作
注:使用Large Object会有安全问题,连接到数据库的用户,即便没有包含大对象所在列的权限,也可以操作这个大对象
Beego orm如何存储图片
看完上面的postgres对于图片的存储,再来看下如何使用beego orm存储一张图片;在beego orm中支持了go的所有基础类型,但是不支持slice;所以,不能直接将[]byte映射到bytea字段上面
好在beego orm提供了一个Fielder接口,可以自定义类型,接口定义如下:
// Fielder define field info
type Fielder interface {
String() string
FieldType() int
SetRaw(interface{}) error
RawValue() interface{}
}
所以,现在就需要定义一个字节数组的类型,然后实现这些接口就好了,代码如下:
type ByteArrayField []byte
// set value
func (e *ByteArrayField) SetRaw(value interface{}) error {
if value == nil {
return nil
}
switch d := value.(type) {
case []byte:
*e = d
case string:
*e = []byte(d)
default:
return fmt.Errorf("[ByteArrayField] unsupported type")
}
return nil
}
func (e *ByteArrayField) RawValue() interface{} {
return *e
}
// specified type
func (f *ByteArrayField) FieldType() int {
return orm.TypeTextField
}
func (f *ByteArrayField) String() string {
return string(*f)
}
然后,我们就可以在struct中进行映射了,如下:
type ImageModel struct{
ImageName string `orm:"column(image_name)"`
ImageData ByteArrayField `orm:"column(image_data);type(bytea)"`
}
这样就可以使用orm的接口操作imageModel,向数据库插入图片,或者从数据库读出图片的内容了
来源:https://juejin.cn/post/7225440252910501925


猜你喜欢
- Python生产者消费者模型一、消费模式生产者消费者模式 是Controlnet网络 * 有的一种传输数据的模式。用于两个CPU之间传输数据,
- 编写一个名为 collatz()的函数,它有一个名为 number 的参数。如果参数是偶数,那么 collatz()就打印出 number
- 数据格式:(polygon.txt) 里面含有2个多边形,一行是一个点 0.085, 0.834, 0.024, 0.744, 0, 0.6
- 本文详细汇总了MySQL学习中的各类技巧,分享给大家供大家参考。具体如下:/* 启动MySQL */net start mysql/* 连接
- 1.简介: SQL Server 2005中的窗口函数帮助你迅速查看不同级别的聚合,通过它可以非常方便地累计总数、移动平均值、以及执行其它计
- 前言数组类型是各种编程语言中基本的数组结构了,本文来盘点下Python中各种“数组”类型的实现。listtuplearray.arrayst
- import os os.os.listdir(path) 然后再一个一个的分析文件和目录 通过和dos命令dir的巧妙结合,可以很轻松的做
- 全局,动态,默认值-1表示自动调整大小,公式:8 + (max_connections / 100)。最小值0,最大值16384,查看当前:
- 如何让你的CSS代码更具有组织性和易维护性,为什么你的样式表总是臃肿和混乱的?有些时候是源于一开始书写时的混乱和草率,有时候也是因为后期的维
- 安装完python之后,我们可以做两件事情,1.将安装目录中的Doc目录下的python331.chm使用手册复制到桌面上,方便学习和查阅2
- 本来想把这个页面用jade渲染出来、评论部分用vue,但是想了想觉得麻烦,最后还是整个用vue的组件搞定他吧。 先上在线demo:http:
- 修改my.ini或my.conf,将sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_US
- 标题: Microsoft SQL Server Management Studio ---------------------------
- 1、最小二乘也可以拟合二次函数我们都知道用最小二乘拟合线性函数没有问题,那么能不能拟合二次函数甚至更高次的函数呢?答案当然是可以的。下面我们
- 如果在session级保存一个dictionary对象会降低系统的性能,而在application级保存一个dictionary对象会导致w
- 我完成了更新我们在 Neutron的实时收入统计。在我花了一周的时间完成并且更新了我们的PHP脚本之后,我最终认决定开始使用Py
- python输入错误怎么删除?python常用的输入函数raw_input()在输入的过程中如果输错了,不能像在命令行下那样backspac
- 基本设置class Map3D( # 初始化配置项,参考 `global_options.InitOpts` &n
- 前言js是一门弱类型的语言,它的强制类型转换的迷惑性也被人诟病,例如标题提到的一个小例子,我想可能很难再找到其他的语言,允许我们觉到一个值似
- 本文实例为大家分享了python定时发送邮件的具体代码,供大家参考,具体内容如下全部代码如下:import timefrom datetim