1,在pojo中使用byte[] 数组来进行保存blob对象
2,用apache fileupload来进行文件上传操作
3,java 类获取绝对路径的方法
Class.class.getResource("/").toString(),这样要用indexof获取web-inf的位置,并将file:\这几个前缀删掉
Class.class.getResource("/").getPath(),前面没有file前缀
4,在sql xml中添加typeHandler
<result property="image" column="IMAGE"
typeHandler="org.springframework.orm.ibatis.support.BlobByteArrayTypeHandler" />
5,bytes to file 的方法
InputStream inputStream = new ByteArrayInputStream(image);
filePath = Action.class.getResource("/").getPath();
filePath = filePath + "/upload/" + user + ".jpg";
FileOutputStream out = new FileOutputStream(filePath);
byte[] b = new byte[1024*1024];
int length = 0;
while((length = inputStream.read(b)) != -1) {
out.write(b, 0, length);
}
out.close();
6,文件上传
String realPath = getServletContext().getRealPaht("/Temp");
DiskFileItemFactory factory = new DisFileItemFactory(1024*1024, new File(readPath));
ServletFileUpload fileUpload = new ServletFileUpload(factory);
List<FIleItem> list = fileUpload.parseRequest(request);
for(FileItem fileItem : list) {
if(fileItem.isFormField()) {//普通表单项
String fieldName = fileItem.getFieldName();
String value = fileItem.getString("UTF-8");
} else {//上传文件
String fieldName = fileItem.getFieldName();
InputStream in = fileItem.getInputStream();//从页面获取的文件
String path = getServletContext().getRealPath("");
FileOutputStream out = new FileOutputStream(path+"/uploadTemp/"+newFileName+".jpg");//将页面上传的文件存储到服务器的文件夹上
byte[] b = new byte[1024*1024];
int length = 0;
while((length = in.read(b)) != -1) {
out.write(b, 0, length);
}
//将服务器上的这个文件转换成byte数组
FileImageInputStream inFile = new FileImageInputStream(new File(path+"/uploadTemp/"+newFileName+".jpg"));
ByteArrayOutputStream byteArr = new ByteArrayOutputStream();
while((length = inFile.read(b)) != -1) {
byteArr(b, 0, length);
}
byte[] photo = byteArr.toByteArray();
//存储数据库,略
fileItem.delete();
in.close();
out.close();
终极方案:当使用spring定时器时,request和ServletContext无法获取,可以用下面的办法直接获取ServletContext:
ContextLoader.getCurrentWebApplicationContext().getServletContext();
在George项目中的使用总结:
读写文件的时候可能需要获得路径,比如上传文件的时候就需要输出流。而通过ServletContext不可以直接获得输出流的,但可以直接获取文件的实际路径。如:
servletContext.getRealPath("/");
这样获得的路径是${context}/的路径,可以依据子路径和文件名称拼接获取输出流