将图片上传到服务器(注意:longBlob和Blob可保留的大小不同,longBlob可存储的大小为4GB,而Blob只有65k,根据自己的需求设置字段类型


这里以springmvc+hibernate为例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/***
* 上传文件
* 用@RequestParam注解来指定表单上的file为MultipartFile
* @param file
* @return
*/
@RequestMapping("/fileUpload")
public String fileUpload(@RequestParam("file") MultipartFile file) {
// 判断文件是否为空
if (!file.isEmpty()) {
try(FileInputStream fis = new FileInputStream(file);) {
// 限制文件大小不超过65k
long size = fis.available();
if(size > 65 * 1024) {
return "more than MaxSize";
}
// Hibernate 3使用Hibernate.createBlob(fis),Hibernate 4已经弃用,使用如下方法:
LobHelper lh = session.getLobHelper();
byte[] b = new byte[(int) size];
fis.read(b);
Blob blob = lh.createBlob(b);
// 假设这里要保存用户头像
User user = new User();
user.setPortrait(blob);
Session session = HibernateSessionFactory.getSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
}
}
// 返回结果
return "SUCCESS";
}
客户端读取图片
1
<img src="showimage?userId = 1" id="image" width="100px" height="100px"></img>
服务端读取blob图片文件(注意:返回的是流的形式)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/***
* 读取图片
* 用@RequestParam
* @param userId
* @return
*/
@RequestMapping("/showimage")
public @ResponseBody InputStream showImage(@RequestParam("userId") Long userId) {
User user = null;
try {
Session session = HibernateSessionFactory.getSession();
user = (User) session.get(User.class, id);
if (null == user)
return null;
session.close;
} catch (Exception e) {
e.printStackTrace();
}
Blob blob = user.getPortrait();
byte[] data = null;
PrintWriter out = null;
// 可以将流写到文件中然后把文件地址返回给客户端去访问,这里将以流的形式返回给客户端
InputStream inputStream = null;
try(InputStream is = blob.getBinaryStream();) {
int length = (int) blob.length();
data = new byte[length];
is.read(data);
out = response.getWriter();
inputStream = new ByteArrayInputStream(data);
int a = inputStream.read();
while (a != -1) {
out.print((char) a);
// 以流的形式返回给客户端
a = inputStream.read();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(null != out) {
out.flush();
out.close();
}
if (null != inputStream) {
inputStream.cloase();
}
}
}