摸索了一个多星期,终于解决了展示瀑布流照片墙的问题,我一直在思考照片放在哪里,前后想了很多方案。最开始是想把照片放在本地(我的E盘中),而数据库中只存照片的名字,但是这种方案遇到了瓶颈,我不知道img标签的src路径怎么写,不能直接写我本地的路径,在网上看了很多,说是要把图片放到服务器下。但是这样我又遇到了一个问题(问题真是频繁啊),因为我创建的是maven工程,之前把maven工程部署到自己配置的tomcat服务器上的时候各种错误,并且也没解决这个问题,我只好将maven工程部署到了STS自带的tomcat服务器上,那现在要把图片放在服务器的目录下,就需要找到tomcat的webapp目录,自己配置的服务器的话这个目录很好找,但是STS自带的tomcat服务器这个目录我又不知道在哪里,所以这种方案又放弃了。既然我找不到这个目录,网上又说可以把自己的某个文件夹当做服务器下的文件夹,所以把我想修改tomcat的server.xml文件,同样是由于找不到STS自带的tomcat服务器下的这个目录,所以这种方案我研究了很久还是不行。后来我又想着还是把图片转换成二进制流存到数据库里面吧,然后再从数据库中读出来,之前我一直想着把图片信息转换成json字符串传递到前台,传递到前台这个过程我是做到了,但是如何在前台将图片的二进制信息转换成图片显示呢,这个过程我又纠结了很久,我一直在想着在js中如何将图片的二进制流转换成图片显示,但是在网上找了很久之后,大家有的说js不能处理二进制流,这种办法也不适用。
后来是通过把图片二进制信息写入到HttpServletResponse 的outputStream输出流中来展示的,最开始我只是在SpringMVC的一个controller中来处理这个过程,将这一个controller中同时处理,然后返回jsp页面,发现根本不行啊,下面是我当时错误的代码形式:
[java] view plain copy print?
<span style="font-family:Comic Sans MS;"> @RequestMapping(value="/toLookImage",method = RequestMethod.GET)
public String lookImage(@PathParam("id")int id,HttpServletRequest request,HttpServletResponse response,Model model){
HttpSession seesion = request.getSession();
Photo photo=photoService.getPhotoById(new BigDecimal(id));
byte[] data=photo.getPhotoData();
response.setContentType("img/jpeg");
response.setCharacterEncoding("utf-8");
try {
OutputStream outputStream=response.getOutputStream();
InputStream in=new ByteArrayInputStream(data);
int len=0;
byte[]buf=new byte[1024];
while((len=in.read(buf,0,1024))!=-1){
<span style="color:#cc0000;"><strong>outputStream.write(buf, 0, len);</strong></span>
}
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "test";
}</span>
其中test.jsp便是我要显示图片的页面,原来我犯了很蠢的错误,应该让一个Controller来返回页面,另一个Controller来显示图片。终于这样我实现了从数据库中读取图片然后显示到页面上。下面来展示下我正确的代码流程:
(1)首先将图片上传然后存到数据库中,代码如下:
[java] view plain copy print?
<span style="font-family:Comic Sans MS;">@Controller
@Configuration
@ImportResource("classpath:spring.xml")
@RequestMapping("/photo")
public class FileUploadController {
@Resource
private IPhotoService photoService;
@RequestMapping(value="/tofile")
public String toFileUpLoad(HttpServletRequest request,Model model){
return "fileUpLoad";
}
//@Value("#{settings['picPath.picUrl']}")
@Value("${picUrl}")
private String picUrl;
public void setPicUrl(String picUrl) {
this.picUrl = picUrl;
}
@RequestMapping("/addAction.do")
@ResponseBody//将返回结果写到response中
public String save(HttpServletRequest request,HttpServletResponse response,Model model,@RequestParam(value="photo",required=false)MultipartFile filedata) throws UnsupportedEncodingException{
if(filedata!=null&&!filedata.isEmpty()){
//获取图片的文件名
String fileName=filedata.getOriginalFilename();
//获取图片的扩展名
String extensionName=fileName.substring(fileName.lastIndexOf(".")+1);
//新的图片名=获取时间戳+"."图片扩展名
String newFileName=String.valueOf(System.currentTimeMillis())+"."+extensionName;
System.out.println(picUrl);
//将图片上传到服务器
//saveFile(newFileName,filedata);
saveFile(request,fileName,filedata);
//将图片名称保存至数据库
<span style="color:#cc0000;"><strong>photoService.insert(fileName,filedata.getBytes());</strong></span>
//图片路径
String realPath=request.getSession().getServletContext().getRealPath(picUrl+"\\"+newFileName);
System.out.println("cddd:"+realPath);
}
JSONArray jsonArray=new JSONArray();
for(int i=3;i<4;i++){
Photo p=photoService.getPhotoById(new BigDecimal(i));
jsonArray.add(p);
}
return jsonArray.toString();
}
private void saveFile(HttpServletRequest request,String newFileName, MultipartFile filedata) {
//根据配置文件获取服务器图片存放路径
String saveFilePath=picUrl;
//构建文件目录
File tempFile=new File(saveFilePath);
if(!tempFile.exists()){
tempFile.mkdirs();
}
//保存文件到服务器
FileOutputStream fos;
try {
fos = new FileOutputStream(saveFilePath+"\\"+newFileName);
fos.write(filedata.getBytes());
//fos.flush();
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}</span>
图片上传的jsp页面代码如下:
[html] view plain copy print?
<span style="font-family:Comic Sans MS;"><%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/photo.js"></script>
<title>upLoadFile</title>
</head>
<body>
<form action="addAction.do" method="post" enctype="multipart/form-data">
<table>
<tr>
<td width="100" align="right">照片:</td>
<td><input type="file" name="photo"/></td>
</tr>
</table>
<input type="submit" id="pclick"/>
</form>
</body>
</html>