思想:
创建一个数据库:
mysql> use imgs;
Database changed
mysql> create table img(idvarchar(32),oldname varchar(100),
-> newname varchar(100),ip varchar(30),dt varchar(19));
1.写上传页面up.jsp
<body>
<form action="<c:url value='/Up2Servlet'/>"method="post"
enctype="multipart/form-data">
File:<input type="file" name="nm"><br /><input type="submit">
</form>
</body>
2.写上传Servlet Up2Servlet
public class Up2Servlet extends HttpServlet {
private Up2Dao dao= new Up2Dao();
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException {
request.setCharacterEncoding("UTF-8");
String path = getServletContext().getRealPath("/up");
DiskFileItemFactory disk = new DiskFileItemFactory();//声明临时文件
ServletFileUpload sfu = newServletFileUpload(disk);//声明解析request的核心类
//声明一个Map用于传递参数
Map<String,Object> img = new HashMap<String, Object>();
try {
List<FileItem>files = sfu.parseRequest(request);//解析request
FileItem file = files.get(0);
String fileName =file.getName();//获取文件名
fileName =fileName.substring(fileName.lastIndexOf("\\")+1);
img.put("oldname", fileName);
//获取扩展名
String exName =fileName.substring(fileName.lastIndexOf("."));
Stringuuid = UUID.randomUUID().toString().replace("-","");
StringnewName = uuid+exName;//新名字
//计算文件夹名
int hashCode = uuid.hashCode();
String dir1 = Integer.toHexString(hashCode&0xff);
String dir2 = Integer.toHexString((hashCode>>8)&0xff);
//组成目录
String relPath = path+"/"+dir1+"/"+dir2;
//判断目录是否存在
File f = new File(relPath);
if(!f.exists()){
f.mkdirs();
}
FileUtils.copyInputStreamToFile(file.getInputStream(),newFile(f,newName));
img.put("newname",dir1+"/"+dir2+"/"+newName);
img.put("ip", request.getRemoteAddr());
//去保存
dao.save(img);
//重定向到Queryservlet
response.sendRedirect(request.getContextPath()+"/QueryServlet");
}catch(Exception e) {
e.printStackTrace();
}
}
}
3.保存到数据库
public classUp2Dao {
public voidsave(Map<String,Object> img){
String sql = "insert into img values(?,?,?,?,?)";
QueryRunner run = newQueryRunner(DataSourceUtils.getDs());
String id = UUID.randomUUID().toString().replace("-", "");
String dt= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
run.update(sql,id, img.get("oldname"),img.get("newname"),img.get("ip"),dt);
}
}
4.查询数据库的Servlet
publicclassQueryServlet extends HttpServlet {
privatestaticfinallongserialVersionUID= 1L;
private QueryDao dao = new QueryDao();
publicvoiddoGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
List<Map<String,Object>>list = dao.query();
//放到requset中转发
request.setAttribute("list", list);
request.getRequestDispatcher("/jsps/show1.jsp").forward(request,response);
}
}
5.查询数据库的dao
public class QueryDao {
public List<Map<String,Object>> query(){
String sql= "select * from img";
QueryRunner run = new QueryRunner(DataSourceUtils.getDs());
List<Map<String,Object>> list =run.query(sql, newMapListHandler());
return list;
}
}
6.显示页面show.jsp
<style type="text/css">
div {
border: 1px solid red;
float: left;
width: 160px;
height: 180px;
text-align: center;
}
img {
width: 160px;
height: 160px;
}
</style>
</head>
<body>
<c:forEach items="${list}" var="mm"varStatus="idx">
<div>
<a href="<c:url value='/up/${mm.newname}'/>"><img
src="<c:url value='/up/${mm.newname}'/>">
</a>
<c:choose>
<c:when test="${fn:length(mm.oldname)>=6}">
${fn:substring(mm.oldname,0,7) }...
</c:when>
<c:otherwise>
${mm.oldname }
</c:otherwise>
</c:choose>
${mm.ip}
</div>
</c:forEach>
</body>
7.示例