blob文件的存储和读取

一、blob文件的存储

1.实体类:

private byte[] newPhoto;//数据库保存图片

注意返回值类型为字节数组,数据库类型为BLOB;

2.jsp页面

<form:input path="filePhoto" htmlEscape="false" type="file"/>

3.controller文件

 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile multipartFile = multipartRequest.getFile("filePhoto");// 与前端设置的fileDataName属性值一致 String filename = multipartFile.getOriginalFilename();// 文件名称 InputStream is = null; try { //读取文件流 is = multipartFile.getInputStream(); byte[] bytes = FileCopyUtils.copyToByteArray(is); user.setNewPhoto(bytes); } catch (Exception e) { // TODO: handle exception }

二、blob文件从数据库的读取

1.jsp页面

<img alt="照片" src="${ctx}/sys/user/upAndReadImg?id=${user.id}" width="120" height="120">

2.controller文件

public String upAndReadImg(@RequestParam(value="id",required=true)String id,HttpServletResponse response){
	User user=UserUtils.get(id);
	if(user != null){
		byte[] bytes=user.getNewPhoto();
		ServletOutputStream out=null;
			try {
				if (bytes != null && bytes.length > 0) {
					out=response.getOutputStream();
					out.write(bytes);
					out.flush();
				  }
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return null;
	}

 

posted on 2017-06-02 13:33  大山008  阅读(3570)  评论(0编辑  收藏  举报