图片转二进制存入oracle字段类型为Blob(取出二进制转图片并显示),图片带路径

1.带图片路径的图片上传至文件夹并转换为二进制存入oracle数据库字段为Blob类型(图片存入数据库方式,inputstream转blob)

jsp页面:


java控制类:

Blob photo = null;

String imageFilePath=request.getRealPath("/") + "\\temp\\"+ String.valueOf(loginUser.getUser().getId()) + "\\" + path;

//String imageFilePath= request.getRealPath("/") + File.separator + "temp" + File.separator+ String.valueOf(loginUser.getUser().getId()) + File.separator + path;

FileInputStream in = null;

try {
in = new FileInputStream(imageFilePath);
photo = Hibernate.createBlob(in);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != in) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}

2.从数据库取出二进制图片并显示(从数据库取出二进制转图片显示方式,只需输出到页面,blob转byte)

jsp页面:

java类:

byte[] image = (byte[]) request.getAttribute("image");
OperatorDetails loginUser = SpringSecurityUtils.getCurrentUser();
Blob blob = loginUser.getUser().getUserPic();
try {
if(null!=blob)
image = blob.getBytes(1, (int) (blob.length()));

if(null!=image){
ServletOutputStream sout = response.getOutputStream();
sout.write(image); // 将缓冲区的输入输出到页面
sout.flush(); // 输入完毕,清除缓冲
sout.close();
}
} catch (Exception e) {
e.printStackTrace();

}


3.图片转换成byte[]  字节流并存入oracle数据库(图片存入数据库方式,inputstream转byte)

User user = loginUser.getUser();
String path = request.getParameter("userImag");
byte[] bytes=null;
//Blob photo = null;
//String pathFilePath = request.getRealPath("/") + "\\temp\\"+ String.valueOf(loginUser.getUser().getId()) + "\\" + path;
String pathFilePath = request.getRealPath("/")+File.separator+"temp"+File.sepa
rator+user.getId();
FileInputStream in = null;
if (null != user.getId()) {
if (StringUtils.isNotBlank(path)) {
try {
in = new FileInputStream(pathFilePath);
ByteArrayOutputStream os = new ByteArrayOutputStream();

byte[] buff = new byte[100];
int rc = 0;
while ((rc=in.read(buff,0,100)) > 0) {
os.write(buff,0,rc);
}
bytes=os.toByteArray();
// photo =Hibernate.createBlob(in);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != in) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
//photo = jsecService.getUserByLoginName(user.getLoginName()).getUserPic();
}
user.setUserPic(bytes);
Md5PasswordEncoder md5 = new Md5PasswordEncoder();
md5.setEncodeHashAsBase64(false);
if (!request.getParameter("password") .equals("******")) {
user.setPassword(md5.encodePassword(
request.getParameter("password"), user.getLoginName()));
}
user.setUserBirthday(userBirthday);
user.setUserMobile(userMobile);
user.setUserPhone(userPhone);
jsecService.saveUser(user);
        

你可能感兴趣的:(java)