微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

postgresql数据库存储图片文件

postgresql数据库使用bytea类型字段

具体存储时使用的是postgresql自定义函数(存储过程)

函数如下:

create or replace function savepicture(xpicture varchar,xpicname varchar)

returns int as $$

begin

insert in temp_picture(picture,picturename) values(cast(xpicture as bytea),xpicname);

return 1;

end $$ language plpgsql;

部分代码处理

String picture= null;

byte[] data = null;
File file = new File(path);
FileInputStream input = null;
try {
input = new FileInputStream (file);
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buf = new byte[(int)file.length()];
int byteread = 0;
try {
while((byteread = input.read(buf))!=-1){
output.write(buf,byteread);
}
data = output.toByteArray();
picture= binarys(data);
output.close();
input.close();
} catch (IOException e) {
e.printstacktrace();
}
} catch (FileNotFoundException e) {
e.printstacktrace();
}catch (IOException e1) {
e1.printstacktrace();
}


public static String binarys(byte[] bytes){
StringBuffer sbf = new StringBuffer("");
for (int i = 0; i < bytes.length; i++) {
String tmp = Integer.toOctalString(bytes[i] & 0xff);
switch (tmp.length()) {
case 1:
tmp = "\\00" +tmp;
break;
case 2:
tmp = "\\0" +tmp;
break;
case 3:
tmp = "\\" +tmp;
break;
default:
break;
}
sbf.append(tmp);
}

return sbf.toString();
}

postgresql存储二进制数据需要转为3位八进制数据存储。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐