詳解如何使用beego orm在postgres中存儲圖片
Postgres如何存儲文件
postgres提供了兩種不同的方式存儲二進制,要么是使用bytea類型直接存儲二進制,要么就是使用postgres的LargeObject功能;決定使用哪中方式更加適合你,就需要了解這兩種存儲方式有哪些限制
bytea類型
bytea類型在單列中雖然可以支持1GB的容量,但是還是不建議使用bytea去儲存比較大的對象,因為它會占用大量的內存
下面通過一個例子來說明,假如現在要在一個表中存儲圖片名和該圖片的數據,創(chuàng)建表如下:
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);
首先是創(chuàng)建一張表,該表中第二個字段類型為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)當中;如果要刪除大文件所在行,在刪除這行之后,還需要再執(zhí)行刪除大文件的操作
注:使用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{}
}
所以,現在就需要定義一個字節(jié)數組的類型,然后實現這些接口就好了,代碼如下:
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,向數據庫插入圖片,或者從數據庫讀出圖片的內容了
以上就是詳解如何使用beego orm在postgres中存儲圖片的詳細內容,更多關于beego orm postgres存儲圖片的資料請關注腳本之家其它相關文章!
相關文章
關于go-zero單體服務使用泛型簡化注冊Handler路由的問題
這篇文章主要介紹了go-zero單體服務使用泛型簡化注冊Handler路由,涉及到Golang環(huán)境安裝及配置Go Module的相關知識,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-07-07
Golang實現Directional Channel(定向通道)
這篇文章主要介紹了Golang實現Directional Channel(定向通道),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-02-02
在Mac中搭建go語言開發(fā)環(huán)境的操作步驟
go語言在開發(fā)效率和運行效率中的優(yōu)勢讓很多人青睞,所以有傾向打算轉向go語言的開發(fā)。下面介紹在Mac中golang的開發(fā)環(huán)境配置。有需要的可以參考借鑒。2016-08-08
golang HTTP 服務器 處理 日志/Stream流的操作
這篇文章主要介紹了golang HTTP 服務器 處理 日志/Stream流的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12

