做了一个根据fileupload上传图片之后,保存到数据库为:http://localhost:8080/runyu/a/vote/voteQuestion/ReadAddress?imgUrl=1480992954368.jpg
我这里使用springmvc方法直接访问ReadAddress这个方法,然后获取文件名,查询,写入流并显示,代码如下:
/**
* 根据1479805098158.jpg 读取图片
* @param imgUrl
* @return
* @throws Exception
*/
@RequestMapping(value = "/ReadAddress")
public void ReadAddress(String imgUrl, HttpServletResponse response, Model model) throws Exception {
String path = Global.getDirPath();
File folder = new File(path);// 默认目录
if (!folder.exists()) {// 如果文件夹不存在
}
File[] result = searchFile(folder, imgUrl);// 调用方法获得文件数组
for (int i = 0; i < result.length; i++) {// 循环显示文件
File file = result[i];
String absolutePath = file.getAbsolutePath() + " "; // 显示文件绝对路径
// 设置header
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0L);
OutputStream os = response.getOutputStream();
byte[] btImg = null;
btImg = SystemConfigController.getBytes(absolutePath);
os.write(btImg);
os.flush();
os.close();
}
}
//检索文件
public static File[] searchFile(File folder, final String keyWord) {// 递归查找包含关键字的文件
File[] subFolders = folder.listFiles(new FileFilter() {// 运用内部匿名类获得文件
public boolean accept(File pathname) {// 实现FileFilter类的accept方法
if (pathname.isFile())// 如果是文件
countFiles++;
else
// 如果是目录
countFolders++;
if (pathname.isDirectory()
|| (pathname.isFile() && pathname.getName().toLowerCase().contains(keyWord.toLowerCase())))// 目录或文件包含关键字
return true;
return false;
}
});
List<File> result = new ArrayList<File>();// 声明一个集合
for (int i = 0; i < subFolders.length; i++) {// 循环显示文件夹或文件
if (subFolders[i].isFile()) {// 如果是文件则将文件添加到结果列表中
result.add(subFolders[i]);
} else {// 如果是文件夹,则递归调用本方法,然后把所有的文件加到结果列表中
File[] foldResult = searchFile(subFolders[i], keyWord);
for (int j = 0; j < foldResult.length; j++) {// 循环显示文件
result.add(foldResult[j]);// 文件保存到集合中
}
}
}
File files[] = new File[result.size()];// 声明文件数组,长度为集合的长度
result.toArray(files);// 集合数组化
return files;
}
<img src="http://localhost:8080/runyu/a/vote/voteQuestion/ReadAddress?imgUrl=1480992954368.jpg" alt="" />就可以显示~\(≧▽≦)/~啦啦啦