精致小巧的java相册制作方法
本文实例为大家分享了java相册制作方法,供大家参考,具体内容如下
注:
1)html上的图片是静态指定的。当更新了新的图片时必须手工更新。所以使用Servlet读取本地images中的所有图片,动态显示给用户。
2)如果存在中文名的图片,由于get方式无法直接传递中文,会导致出错。
主页面–index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>小小相册</title> </head> <body> <!-- http://localhost:8080/photosWeb/ --> <h2>小小相册</h2> <a href="jsps/upload.jsp">上传相片</a> <a href="<%=request.getContextPath() %>/servlet/showAllImg">浏览相片</a> </body> </html>
页面显示:
上传图片功能:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>小小相册</title> </head> <body> <h2>小小相册</h2> <form action="<%=request.getContextPath() %>/servlet/uploadServlet" method="post" enctype="multipart/form-data"> 照片:<input type="file" name="file"/><br/> 说明:<input type="text" name="desc"/><br/> <input type="submit" value="上传"/> </form> </body> </html>
package cn.hncu.servlet; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; import cn.hncu.dao.PhotoDaoImpl; import cn.hncu.domain.PhotoModel; import cn.hncu.utils.MyUtils; public class UploadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print("错误信息:提交方式错误...不支持Get方式上传照片"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>上传照片页面</TITLE></HEAD>"); out.println(" <BODY>"); //从上传表单提取信息:一,封装成photo值对象,调用dao层存储到后台 // 二,把上传的照片存储到服务器硬盘 //数据库:存储照片的存储情况的信息,,,真正的文件存储到硬盘 DiskFileItemFactory dfi=new DiskFileItemFactory(); File file=new File("d:/a"); if(file.exists()){ file.mkdirs(); } dfi.setRepository(file); ServletFileUpload upload=new ServletFileUpload(dfi); upload.setSizeMax(1024*1024*8); upload.setHeaderEncoding("utf-8");//==>request.setCharacterEncoding("utf-8"); try { List<FileItem> list=upload.parseRequest(request); PhotoModel pm=new PhotoModel(); InputStream in=null; for(FileItem fI:list){ if(fI.isFormField()){//这个不会有临时文件 String desc=fI.getString("utf-8"); pm.setDesc(desc); }else{ in=fI.getInputStream(); // String filename=fI.getFieldName(); // System.out.println("getFieldName:"+filename); String fileName=fI.getName(); // System.out.println("getName:"+fileName);//测试:C:\Users\adl1\Pictures\Saved Pictures\111.jpg? //卫条件 if(fileName==null||fileName.trim().equals("")){ out.println("没有选择文件,,,请必须选择一个文件...<br/>"); String strPath2=request.getContextPath()+"/jsps/upload.jsp"; out.println("<a href=\""+strPath2+"\">返回上传页面</a>"); return; } pm.setDt(MyUtils.getCurrentDataime()); String realName=fileName.substring(fileName.lastIndexOf("\\"));//"\112.jpg" System.out.println(realName.substring(1, realName.length())); pm.setRealName(realName.substring(1, realName.length()));//把realName的"\"去掉 //ext扩展名 String ext=fileName.substring(fileName.lastIndexOf(".")); pm.setExt(ext); String id=MyUtils.getUUID(); pm.setId(id); pm.setIp(request.getRemoteAddr()); pm.setDir(MyUtils.getDir(id)); } } //完成photo值对象的封装,调用dao进行存储 boolean boo=new PhotoDaoImpl().sava(pm); if(boo){ //完成数据库的存储,接下来是服务器硬盘的存储 //把照片存储到项目根目录下的photos文件夹中存储(以打散方式存储) String path="photos/"+pm.getDir(); // System.out.println("path:"+path);//测试:photos/9/0 String filePath=getServletContext().getRealPath(path); // System.out.println("filePath:"+filePath);//测试:D:\apache-tomcat-7.0.30\webapps\photosWeb\photos\9\0 File dir=new File(filePath); if(!dir.exists()){ dir.mkdirs(); } FileUtils.copyInputStreamToFile(in, new File(filePath+"/"+pm.getId()+pm.getExt())); // //如果硬盘保存成功就跳转到主页面--转发 //// RequestDispatcher rd=request.getRequestDispatcher(getServletContext().getContextPath()+"/index.jsp");//"/photosWeb/photosWeb/index.jsp" // RequestDispatcher rd=request.getRequestDispatcher("/index.jsp");//"/photosWeb/index.jsp"g // //java代码块和web.xml中url的开始"/"代表项目根目录 // rd.forward(request, response); //这里不能使用转发,具体重定向和转发区别:http://blog.csdn.net/xanlv/article/details/52701085 //重定向 response.sendRedirect(getServletContext().getContextPath()+"/index.jsp"); }else{ //数据库保存失败--留在上传页面 RequestDispatcher rd=request.getRequestDispatcher("/jsps/upload..jsp");//"/photosWeb/index.jsp" rd.forward(request, response); } } catch (FileUploadException e) { throw new RuntimeException("上传失败", e); }finally{//清临时文件 File f=new File("d:/a"); File fs[]=f.listFiles(); for(File ff:fs){ ff.delete(); } } out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } }
页面显示效果:
浏览图片功能:
package cn.hncu.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.hncu.dao.PhotoDaoImpl; import cn.hncu.domain.PhotoModel; public class ShowAllImgServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>相册浏览</TITLE></HEAD>"); out.println(" <BODY>"); String strPath=request.getContextPath()+"/jsps/upload.jsp"; out.println("<a href=\""+strPath+"\">返回上传页面</a>"); //String table="<table border='1px' width='100%' cellspacing='0' align='center'>"+//这种方式不可以设置水平居中 String table="<table border='1px' width='100%' cellspacing='0' style='text-align: center;'>"+ "<tr><th>文件名</th><th>上传日期时间</th><th>相片</th><th>相片说明</th><th>操作</th></tr>"; out.println(table); //从dao层把所有的照片信息读取出来发送到前端页面 List<PhotoModel> list=new PhotoDaoImpl().getAllPhotos(); for(PhotoModel pm:list){ out.println("<tr>"); out.println("<td width=80>"+pm.getRealName()); out.println("</td>"); out.println("<td width=120>"+pm.getDt()); out.println("</td>"); String path=request.getContextPath()+"/photos/"+pm.getDir()+"/"+pm.getId()+pm.getExt(); //System.out.println(path);//"/photosWeb/photos/d/7/e78e18352b42410f85dbd8df834bd718.jpg" //点击图片可以查看大图 out.println("<td width=100><a href='"+path+"'><img width=100 height=100 src='"+path+"'/></a>"); out.println("</td>"); out.println("<td width=200>"+pm.getDesc()); out.println("</td>"); out.println("<td width=80><a href='"+getServletContext().getContextPath()+"/servlet/delPhoto?id="+pm.getId()+"'>删除图片</a>"); //out.println("<a href='<%=request.getContextPath()%>/servlet/down?id="+pm.getId()+"'>下载图片</a></td>"); out.println("<br/><a href='"+getServletContext().getContextPath()+"/servlet/down?id="+pm.getId()+"'>下载图片</a></td>"); out.println("</tr>"); } out.println("</table>"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print("不支持Post方式。。。"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } }
页面显示效果:
删除功能:
package cn.hncu.servlet; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.hncu.dao.PhotoDaoImpl; import cn.hncu.domain.PhotoModel; public class DelPhotoServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>删除照片页面</TITLE></HEAD>"); out.println(" <BODY>"); String id=request.getParameter("id"); String ip=request.getRemoteAddr(); PhotoDaoImpl dao=new PhotoDaoImpl(); PhotoModel pm=dao.getSingleById(id); if(pm!=null){ if(!pm.getIp().equals(ip)){ out.println("您没有该图片的权限去删除..."); String strPath=request.getContextPath()+"/servlet/showAllImg"; out.println("<br/><a href=\""+strPath+"\">返回继续浏览</a>"); return ; } //删除包含两部分工作:清除数据库中的信息 和 删除服务器硬盘中的图片文件 //1清除数据库中的信息 boolean boo = dao.del(id); //2删除服务器硬盘中的图片文件 if(boo){ String path="photos/"+pm.getDir()+"/"+pm.getId()+pm.getExt(); String filePath=getServletContext().getRealPath(path); File f=new File(filePath); if(f.exists()){ f.delete(); } String strPath=request.getContextPath()+"/servlet/showAllImg"; // System.out.println(strPath);///photosWeb/servlet/showPhotos out.println("删除成功...<br/><a href=\""+strPath+"\">返回浏览</a>"); }else{ out.println("删除数据库信息失败"); } }else{ out.println("文件不存在..."); String strPath=request.getContextPath()+"/servlet/showAllImg"; out.println("<br/><a href=\""+strPath+"\">返回继续浏览</a>"); } out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>删除照片页面</TITLE></HEAD>"); out.println(" <BODY>"); out.print("不支持POST方式..."); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } }
页面显示:
下载功能:
1.在HTML页面上使用超连接指向要下载的文件(不安全容易被盗链)。
问题:
如何确定本地资源?
ServletContext – 代表一个web项目。一个web项目只有一个ServletContext对像。
getRealPath(“/”); //d:/prm/tom/web/
需求分析:
在实际的开发中,下载哪一个文件,都是由用户动态选择的。
如,在我们项目images目录下,存在着很多图片文件。用户在页面上显示所有图片,用户可以点下载连接下载喜欢的图片。
详细设计:
使用静态网页显示所有图片。给每一个图片一个下以下载的超连接。
在超连接后面传递要下载的图片id。
在serivice中动态接收图片名。完成下载 。
package cn.hncu.servlet; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.net.URLEncoder; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import cn.hncu.dao.PhotoDaoImpl; import cn.hncu.domain.PhotoModel; public class DownServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取被下载图片的信息 tring id=request.getParameter("id"); PhotoModel pm=new PhotoDaoImpl().getSingleById(id); if(pm==null){ response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); response.getWriter().println("alert('该文本已不存在...')"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); //getServletContext().getContextPath() RequestDispatcher rd=request.getRequestDispatcher("/servlet/down");//"/photosWeb/index.jsp" //java代码块和web.xml中url的开始"/"代表项目根目录 rd.forward(request, response); }else{ //真正下载: 把服务器硬盘的照片文件读取出来发送给客户端(设置响应头) //获取真实的文件 String realName=pm.getRealName(); realName=URLEncoder.encode(realName, "utf-8");//如果是中文名必须转码,防止文件名中文乱码 // InputStream in=DownServlet.class.getClassLoader().getResourceAsStream(realName); //设置显示类型为下载 response.setContentType("application/force-download"); //设置响应头 response.setHeader("content-Disposition", "attachment;filename=\""+realName+"\""); // String path=request.getContextPath()+"/photos/"+pm.getDir()+"/"+pm.getId()+pm.getExt(); String path="photos/"+pm.getDir()+"/"+pm.getId()+pm.getExt(); String filePath=getServletContext().getRealPath(path); FileUtils.copyInputStreamToFile(request.getInputStream(), new File(filePath)); InputStream in=new FileInputStream(filePath); OutputStream o=response.getOutputStream(); byte b[]=new byte[1024]; int len=0; while((len=in.read(b))!=-1){ o.write(b, 0, len); } o.close(); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" 不支持"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } }
页面显示效果:
配置文件web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name> <servlet> <servlet-name>UploadServlet</servlet-name> <servlet-class>cn.hncu.servlet.UploadServlet</servlet-class> </servlet> <servlet> <servlet-name>ShowAllImgServlet</servlet-name> <servlet-class>cn.hncu.servlet.ShowAllImgServlet</servlet-class> </servlet> <servlet> <servlet-name>DownServlet</servlet-name> <servlet-class>cn.hncu.servlet.DownServlet</servlet-class> </servlet> <servlet> <servlet-name>DelPhotoServlet</servlet-name> <servlet-class>cn.hncu.servlet.DelPhotoServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/servlet/uploadServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ShowAllImgServlet</servlet-name> <url-pattern>/servlet/showAllImg</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>DownServlet</servlet-name> <url-pattern>/servlet/down</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>DelPhotoServlet</servlet-name> <url-pattern>/servlet/delPhoto</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
数据库:photos.xml
<?xml version="1.0" encoding="UTF-8"?> <photos> <!-- 数据库设计 <photo id="uuid" realName="真实文件名.jpg" dT="2016-10-03 19:51:31" ext=".jpg" dir="a/5" ip="192.168.12.12"> <desc>照片说明信息</desc> </photo> --> </photos>
值对象:PhotoModel.java
package cn.hncu.domain; public class PhotoModel { //photo值对象 private String id;//UUID private String realName;//照片真实文件名 private String ext;//扩展名 private String dir;//文件打撒后存储的目录 private String dt;//上传日期时间 private String ip;//上传客户端的ip地址 private String desc;//照片说明 public String getId() { return id; } public void setId(String id) { this.id = id; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public String getExt() { return ext; } public void setExt(String ext) { this.ext = ext; } public String getDir() { return dir; } public void setDir(String dir) { this.dir = dir; } public String getDt() { return dt; } public void setDt(String dt) { this.dt = dt; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String Dreturn desc; } public void setDesc(String desc) { this.desc = desc; } }
dao层:这里简写了,只写了实现类PhotoDaoImpl.java
package cn.hncu.dao; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.dom4j.Document; import org.dom4j.Element; import cn.hncu.domain.PhotoModel; import cn.hncu.utils.DomFactory; public class PhotoDaoImpl { public boolean sava(PhotoModel pm){ Document dom=DomFactory.getDom(); Element root=dom.getRootElement(); Element e=root.addElement("photo"); e.addAttribute("id", pm.getId()); e.addAttribute("dir", pm.getDir()); e.addAttribute("dt", pm.getDt()); e.addAttribute("ext", pm.getExt()); e.addAttribute("ip", pm.getIp()); e.addAttribute("realName", pm.getRealName()); e.addElement("desc").setText(pm.getDesc()); boolean b=DomFactory.save(); if(b){ return true; } return false; } public List<PhotoModel> getAllPhotos(){ List<PhotoModel> li=new ArrayList<PhotoModel>(); Document dom=DomFactory.getDom(); Element e=dom.getRootElement(); Iterator<Element> it=e.elementIterator(); while(it.hasNext()){ Element ie=it.next(); PhotoModel pm=new PhotoModel(); pm.setId(ie.attributeValue("id")); pm.setDir(ie.attributeValue("dir")); pm.setDt(ie.attributeValue("dt")); pm.setExt(ie.attributeValue("ext")); pm.setIp(ie.attributeValue("ip")); pm.setRealName(ie.attributeValue("realName")); pm.setDesc(ie.elementText("desc")); li.add(pm); } return li; } public PhotoModel getSingleById(String id){ List<PhotoModel> li=getAllPhotos(); PhotoModel pm=new PhotoModel(); for(PhotoModel p:li){ if(p.getId().equals(id)){ return p; } } return null; } public boolean del(String id) { Document dom=DomFactory.getDom(); Element e=(Element) dom.selectSingleNode("//photo[@id='"+id+"']"); return e.getParent().remove(e); } }
工具类:
1.
package cn.hncu.utils; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; public class MyUtils { private MyUtils() { } public static String getUUID(){ return UUID.randomUUID().toString().replace("-", ""); } private static SimpleDateFormat sdf=new SimpleDateFormat("yy-MM-dd HH:mm:ss"); public static String getCurrentDataime(){ return sdf.format(new Date()); } public static String getDir(String uuid){ String dir1=Integer.toHexString(uuid.hashCode()&0xf); String dir2=Integer.toHexString((uuid.hashCode()&0xf0)>>4); return dir1+"/"+dir2; } }
2.
package cn.hncu.utils; import java.io.FileOutputStream; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class DomFactory { private static Document dom; private static String fileName; static{ try { SAXReader r=new SAXReader(); //获取src下的资源文件 fileName=DomFactory.class.getClassLoader().getResource("photos.xml").getPath(); System.out.println("users.xml的路径:"+fileName);//"/D:/apache-tomcat-7.0.30/webapps/photosWeb/WEB-INF/classes/photos.xml" //注意:获取tomcat中当前项目classpath下的资源方式 dom=r.read(fileName); } catch (DocumentException e) { e.printStackTrace(); } } public static Document getDom(){ return dom; } public static boolean save(){ XMLWriter w; try { w = new XMLWriter(new FileOutputStream(fileName)); w.write(dom); w.close(); return true; } catch (Exception e) { return false; } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)