Writing a Java version of simple cloud album, the functions implemented are:
Users can upload one to multiple files at a time.
Users can download pictures uploaded by others.
Users can view pictures of everyone else.
Users can only delete pictures uploaded through their own IP.
Techniques used:
File upload and download, design mode, Dom4j, xPath, etc.
Let’s look at the next two pages:
source code:
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.servlets.UploadServlet</servlet-class> </servlet> <servlet> <servlet-name>cloudPhotoServlet</servlet-name> <servlet-class>cn.hncu.servlets.cloudPhotoServlet</servlet-class> </servlet> <servlet> <servlet-name>DownServlet</servlet-name> <servlet-class>cn.hncu.servlets.DownServlet</servlet-class> </servlet> <servlet> <servlet-name>DelServlet</servlet-name> <servlet-class>cn.hncu.servlets.DelServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/upload</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>cloudPhotoServlet</servlet-name> <url-pattern>/cloudPhoto</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-mapping> <servlet-name>DownServlet</servlet-name> <url-pattern>/servlet/DownServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>DelServlet</servlet-name> <url-pattern>/servlet/DelServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>chx Cloud Album</title> <script type="text/javascript"> function delFile(input){ table = input.parentElement.parentElement.parentElement;//table.nodeName TBODY table.removeChild(input.parentElement.parentElement); } var t=1; function addFile(input){ tr = input.parentElement.parentElement; //alert(tr.nodeName); var str = "<td>Select file: </td>"+ "<td> <input type='file' name='file"+t+"'> </td> "+ "<td>File description: </td>"+ "<td> <input type='text' name='text"+t+"'> </td> "+ "<td> <input type='button' value='Delete file' onclick='delFile(this)'> </td>"; tr.insertAdjacentHTML("beforeBegin",str); } function move(){ window.location.href="/myPhoto/cloudPhoto"; } </script> <style type="text/css"> #font{ color:red; } </style> </head> <body> <h1><font id="font"> Album upload: </font></h1> <form action="/myPhoto/upload" method="post" enctype="multipart/form-data"> <table> <tr> <td>Select file: </td> <td> <input type="file" name="file1"> </td> <td> File description: </td> <td> <input type="text" name="text1"> </td> <td> <input type="button" value="delete file" onclick="delFile(this)"> </td> </tr> <tr> <td colspan=2> <input type="submit" value="upload file"> </td> <td colspan=3> <input type="button" value="add file" onclick="addFile(this)"> </td> </tr> </table> </form> <form action="/myPhoto/cloudPhoto" method="post" enctype="multipart/form-data"> <table> <tr> <td colspan=5><input type="submit" value="enter the cloud album" onclick="move()"></td> </tr> </table> </form> </body></html>photo.xml:
<?xml version="1.0" encoding="UTF-8"?><photos></photos>
MyUtils.java:
package cn.hncu.utils;import java.text.SimpleDateFormat;import java.util.Date;import java.util.UUID;public class MyUtils { /** * @return Get UUID */ public static String getUUID(){ return UUID.randomUUID().toString().replace("-", ""); } /** * @param uuid * @return Get the broken path through uuid */ public static String getDir(String uuid){ String dir1 = Integer.toHexString( uuid.hashCode() & 0xf ); String dir2 = Integer.toHexString( (uuid.hashCode() & 0xf0)>>4 ); return "/"+dir1+"/"+dir2; } //Date-time format private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyy year MM month dd date HH:mm:ss"); /** * @return Returns the date and time when uploading*/ public static String getCurrentDateTime(){ return sdf.format(new Date()); }}Dom4jFactory.java:
package cn.hncu.utils;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.UnsupportedEncodingException;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.Node;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;public class Dom4jFactory { private static Document dom=null; private static String path; // Static block! Will only run once! The feature is that when the class is loaded, static{ try { SAXReader sax = new SAXReader() is executed; //Because our resources have been published from myelipse to the tomcat server, it is different from the original pure Java project. //Use the current class to find its class loader, and then obtain the resource path through the class loader. path = Dom4jFactory.class.getClassLoader().getResource("photo.xml").getPath(); //getClassLoader() returns: loading the class loader of the class or interface represented by this object//public URL getResource(String name) returns: reading the URL object of the resource; if the resource cannot be found, or the caller does not have enough permission to obtain the resource, return null. //This method first searches for the resource's parent class loader; if the parent class loader is null, the search path is the path of the virtual machine's built-in class loader. //public String getPath() gets the path part of this URL. System.out.println(path); dom = sax.read(new FileInputStream(path)); } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (DocumentException e) { throw new RuntimeException(e); } } /** * @return Get the Document of the album */ public static Document getDocument(){ return dom; } /** * Save photo.xml and save to local */ public static boolean save(){ try { XMLWriter w = new XMLWriter(new FileOutputStream(path)); w.write(dom); w.close(); return true; } catch (UnsupportedEncodingException e) { return false; } catch (FileNotFoundException e) { return false; } catch (IOException e) { return false; } } public static boolean del(String uuid){ Node node = dom.selectSingleNode("[@uuid='"+uuid+"']"); if(node==null){ return false; } node.getParent().remove(node); return true; } /** * Test* @param args */ public static void main(String[] args){ System.out.println( getDocument() ); }}PhotoModel.java - Value Object
package cn.hncu.domain;/** * Value object encapsulation* @author Chen Haoxiang* 2016-7-24 */public class PhotoModel { private String uuid;//uuid private String realName="";//The real file name of the picture (file name when uploading) private String ext;//The suffix name private String dir;//The path after breaking private String dateTime;//The time of uploading file private String ip;//The uploader's IP private String desc;//The file description public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } 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 getDateTime() { return dateTime; } public void setDateTime(String dateTime) { this.dateTime = dateTime; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } @Override public String toString() { return "PhotoModel [uuid=" + uuid + ", realName=" + realName + ", ext=" + ext + ", dir=" + dir + ", dateTime=" + dateTime + ", ip=" + ip + ", desc=" + desc + "]"; }}PhotoDao.java:
package cn.hncu.photoDao.Dao;import java.util.List;import cn.hncu.domain.PhotoModel;public interface PhotoDao { /** * @param photo * @return Save data*/ public boolean save(PhotoModel photo); /** * @return Return all picture information*/ public List<PhotoModel> getAll(); /** * @param uuid * @return Find the encapsulated value object through uuid*/ public PhotoModel getSingleByUuid(String uuid); /** * @param uuid * @return Delete the information of the image in photos.xml through uuid */ public boolean deleteXml(String uuid); /** * @param dir * @return Delete the information of the image in the server disk through the path */ public boolean deleteFile(String pathFileName);}PhotoSerImpl.java:
package cn.hncu.photoDao.impl;import java.io.File;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.Node;import cn.hncu.domain.PhotoModel;import cn.hncu.photoDao.Dao.PhotoDao;import cn.hncu.utils.Dom4jFactory;public class PhotoSerImpl implements PhotoDao{ @Override public boolean save(PhotoModel photo) { Document dom = Dom4jFactory.getDocument(); Element root = dom.getRootElement(); //Add attribute Element p = root.addElement("photo"); p.addAttribute("uuid", photo.getUuid()); p.addAttribute("realName", photo.getRealName()); p.addAttribute("dateTime", photo.getDateTime()); p.addAttribute("ip", photo.getIp()); p.addAttribute("ext", photo.getExt()); p.addAttribute("dir", photo.getDir()); p.addAttribute("desc", photo.getDesc()); return Dom4jFactory.save(); } @Override public List<PhotoModel> getAll() { List<PhotoModel> list = new ArrayList<PhotoModel>(); Document dom = Dom4jFactory.getDocument(); Element root = dom.getRootElement(); Iterator<Element> it = root.elementIterator("photo"); //Get the iterator of the photo element through DOM4J, and you can also find all photos through xPath //List<Node> lists = dom.selectNodes("//photo[@uuid]"); //Iterator<Node> it = lists.iterator(); while(it.hasNext()){ Element e = it.next(); PhotoModel photo = new PhotoModel(); photo.setUuid(e.attributeValue("uuid")); photo.setRealName(e.attributeValue("realName")); photo.setDateTime(e.attributeValue("dateTime")); photo.setExt(e.attributeValue("ext")); photo.setIp(e.attributeValue("ip")); photo.setDir(e.attributeValue("dir")); photo.setDesc(e.attributeValue("desc")); list.add(photo); } return list; } @Override public PhotoModel getSingleByUuid(String uuid) { List<PhotoModel> photos=getAll(); for(PhotoModel photo:photos){ if(photo.getUuid().equals(uuid)){ return photo; } } return null; } @Override public boolean deleteXml(String uuid) { Document dom = Dom4jFactory.getDocument(); Element e = (Element) dom.selectSingleNode("//photo[@uuid='"+uuid.trim()+"']"); return e.getParent().remove(e); } @Override public boolean deleteFile(String pathFileName) { try { File file = new File(pathFileName); if(file.exists()){ file.delete(); } return true; } catch (Exception e) { return false; } }}PhotoDaoFactory.java:
package cn.hncu.photoDao.factory;import cn.hncu.photoDao.impl.PhotoSerImpl;/** * Factory method* @author Chen Haoxiang* 2016-7-24 */public class PhotoDaoFactory { public static PhotoSerImpl getPhotoDao(){ return new PhotoSerImpl(); }}UploadServlet.java:
package cn.hncu.servlets;import java.io.File;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 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 cn.hncu.domain.PhotoModel;import cn.hncu.photoDao.Dao.PhotoDao;import cn.hncu.photoDao.factory.PhotoDaoFactory;import cn.hncu.utils.Dom4jFactory;import cn.hncu.utils.MyUtils;public class UploadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); response.getWriter().print("<h1>Sorry, this page does not support GET access!!!</h1>"); response.getWriter().print("<a href='javascript:history.go(-1)'>Return to previous page</a> "); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); final PrintWriter out = response.getWriter(); //Anti-black-non-multipart form submission//Use upload tool boolean boo = ServletFileUpload.isMultipartContent(request); if(!boo){ out.print("<h1> does not support the submission method of ordinary forms! </h1>"); return; } File file = new File("d:/photoCache"); if(!file.exists()){ file.mkdir(); } DiskFileItemFactory fiFactory = new DiskFileItemFactory(1024*10,file); ServletFileUpload upload = new ServletFileUpload(fiFactory); upload.setHeaderEncoding("utf-8");//Set file name encoding String path = getServletContext().getRealPath("/photos"); FileItem fi = null; try { List<FileItem> list = upload.parseRequest(request); PhotoModel photo = new PhotoModel();//Data encapsulation---7 properties are required photo.setRealName(""); int cont=0; for(FileItem f:list){ if(cont!=0 && cont%2==0 && !photo.getRealName().equals("")){ photo = new PhotoModel();//Re-data encapsulation} fi=f; if(fi.isFormField()){//Normal form component//Get file description String desc = fi.getString("utf-8"); photo.setDesc(desc);//#1 }else{ //Anti-black 3-If the file is not selected in the file component if(fi.getSize()==0){ photo.setRealName(""); cont++; continue; } String fileName = fi.getName(); fileName = fileName.substring( fileName.lastIndexOf("//")+1);//Real file name photo.setRealName(fileName);//#2 String ext = fileName.substring(fileName.lastIndexOf("."));//Extension photo.setExt(ext);//#3 photo.setDateTime(MyUtils.getCurrentDateTime());//#4 photo.setIp( request.getRemoteAddr() );//#5 String uuid = MyUtils.getUUID(); photo.setUuid(uuid);//#6 photo.setDir(MyUtils.getDir(uuid) );//#7 //Disrupt the directory File dFile = new File(path+photo.getDir()); if(!dFile.exists()){ dFile.mkdir(); } fi.write(new File(path+photo.getDir()+"/"+photo.getUuid()+photo.getExt())); } cont++; if(cont%2==0 && !photo.getRealName().equals("")){ PhotoDao dao = PhotoDaoFactory.getPhotoDao(); boo = dao.save(photo); //Save to disk - Method 2: FileUtils.copyInputStreamToFile(in, new File(fileName2));//※2※Storing the image file to the server hard disk photo = new PhotoModel();//Re-encapsulation} } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally{ if(fi!=null){ fi.delete(); } if(Dom4jFactory.save()){ out.print("<h1>Uploaded successfully! </h1>"); out.print("<a href='javascript:history.go(-1)'>Return to previous page</a> "); }else{ out.print("<h1>Upload failed!</h1>"); out.print("<a href='javascript:history.go(-1)'>Return to previous page</a> "); } } }}Show all files -cloudPhotoServlet.java
package cn.hncu.servlets;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.domain.PhotoModel;import cn.hncu.photoDao.Dao.PhotoDao;import cn.hncu.photoDao.factory.PhotoDaoFactory;public class cloudPhotoServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pwd = (String) request.getParameter("pwd"); if ("chx".equals(pwd)) { doPost(request, response); } else { response.setContentType("text/html;charset=utf-8"); response.getWriter().print("<h1>Sorry, you do not have permission to access!!!</h1>"); } } 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>CHX Cloud Album</TITLE></HEAD>"); out.println(" <BODY>"); out.println("<table border='1px;double;#ff0000'>"); out.println("<tr>"); out.println("<tr>"); out.println("<td>File Name</td>"); out.println("<td>upload time"); out.println("<td>file</td>"); out.println("<td>file description</td>"); out.println("<td>operation</td> "); out.println("</tr>"); String tdWH = "style='width:200px; height:200px;'"; // Show all pictures PhotoDao dao = PhotoDaoFactory.getPhotoDao(); List<PhotoModel> photos = dao.getAll(); for (PhotoModel photo : photos) { String fileName = photo.getRealName(); String time = photo.getDateTime(); // Output picture String path = request.getContextPath() + "/photos/" + photo.getDir() + "/" + photo.getUuid() + photo.getExt(); // System.out.println(path); // /myPhoto/photos//7/c/a1237a48a6aa451cb22fa78b15bafcea.jpg String img = "<a href='" + path + "'><img src='" + path + "'/></a>"; String desc = photo.getDesc(); String delStr = "<a href='/myPhoto/servlet/DelServlet?uuid=" + photo.getUuid() + "'>Delete</a>"; String downStr = "<a href='/myPhoto/servlet/DownServlet?uuid=" + photo.getUuid() + "'>Download</a>"; out.println("<td " + tdWH + "> " + fileName + " </td>"); out.println("<td " + tdWH + ">" + time + "</td>"); out.println("<td " + tdWH + ">" + img + "</td>"); out.println("<td " + tdWH + ">" + desc + "</td>"); out.println("<td " + tdWH + ">" + delStr + "" + downStr + "</td>"); out.println("</tr>"); } out.println("<tr>"); out.println("</tr>"); out.println("</table>"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); }}Delete file - DelServlet.java
package cn.hncu.servlets;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.domain.PhotoModel;import cn.hncu.photoDao.Dao.PhotoDao;import cn.hncu.photoDao.factory.PhotoDaoFactory;public class DelServlet extends HttpServlet { //Inject private PhotoDao dao = PhotoDaoFactory.getPhotoDao(); public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String uuid = request.getParameter("uuid"); String ip = request.getRemoteAddr(); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); PhotoModel photo = dao.getSingleByUuid(uuid); if(photo!=null){ if(!photo.getIp().equals(ip)){ out.print("<h1>You do not have permission to delete this file! ! ! </h1>"); out.print("<a href='javascript:history.go(-1)'>Return to previous page</a> "); return ; } //1. Delete information in the database boolean boo = dao.deleteXml(uuid); if(boo){ String fileName = "photos/"+photo.getDir()+"/"+photo.getUuid()+photo.getExt(); String pathFileName = getServletContext().getRealPath(fileName); if(dao.deleteFile(pathFileName)){ //Redirect to the album page response.sendRedirect("/myPhoto/cloudPhoto?pwd=chx"); }else{ out.print("<h1> cannot be deleted from the server, the file is being occupied!!!</h1>"); out.print("<a href='javascript:history.go(-1)'>Return to the previous page</a> "); } }else{ out.print("<h1>The file no longer exists!!!</h1>"); out.print("<a href='javascript:history.go(-1)'>Return to the previous page</a> "); } } }}Download file -DownServlet.java
package cn.hncu.servlets;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.URLEncoder;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import cn.hncu.domain.PhotoModel;import cn.hncu.photoDao.Dao.PhotoDao;import cn.hncu.photoDao.factory.PhotoDaoFactory;public class DownServlet extends HttpServlet { private PhotoDao dao = PhotoDaoFactory.getPhotoDao(); public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String uuid = request.getParameter("uuid"); System.out.println(uuid); PhotoModel photo = dao.getSingleByUuid(uuid); System.out.println(photo); if(photo!=null){ //Set the response header--Content Receiver--When the browser sees this response header, it will open the download program it thinks is //(If Thunder is recognized, Thunder will automatically open, if not, a "Save File As" dialog box will be opened) response.setContentType("application/force-download"); String realName = photo.getRealName(); String agent = request.getHeader("User-Agent"); System.out.println(agent); if(agent.indexOf("Mozilla")!=-1){//Firefox browser response.setHeader("Content-Disposition", "attachment;filename="+ new String(realName.getBytes("GB2312"),"ISO-8859-1")); }else{ //Solve the problem of garbled Chinese (just use the following sentence to encode the file name) realName = URLEncoder.encode(realName, "utf-8");//Use the specified encoding mechanism to convert the string to application/x-www-form-urlencoded format. response.setHeader("Content-Disposition", "attachment;filename=/""+realName+"/""); //Note: "cttachment;" cannot be missing, otherwise the browser will open directly in a new window} String fileName = "photos/" + photo.getDir()+"/"+photo.getUuid()+photo.getExt(); String pathFileName = getServletContext().getRealPath(fileName); InputStream in = new FileInputStream(pathFileName); OutputStream out = response.getOutputStream(); byte buf[] = new byte[2048]; int len=0; while( (len=in.read(buf))!=-1 ){ out.write(buf, 0, len); } out.close(); in.close(); }else{ response.setContentType("text/html;charset=utf-8"); response.getWriter().println("<h1>This file has been deleted</h1>"); } }}Demonstration results
I won't demonstrate this, there are pictures in front of it, and I've given all the source codes. If you are interested, you can make some improvements by yourself.
In fact, this can also upload any other type of files, because we do not have a protective suffix name, and we use character streaming to transmit it, and it will not be distorted (it can be processed as a cloud disk~~)! !
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.