Upload, download and management technology of functional files: 1. Use xml as database storage information (dom4j, xpath)
2. Upload and download of Java forms
3. Breaking down the file directory (the Hash directory is a method to optimize file storage performance)
Need jar package:
commons-fileupload-1.2.2.jar, commons-io-2.1.jar, dom4j-1.6.1.jar and jaxen-1.1-beta-6.jar
--------------------------------------------------------------------------------
Write index.jsp first
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>Album Management System</title> </head> <body> <h1>My Album</h1> <a href="jsps/upload.jsp">Upload Album</a> <a href="servlets/ShowServlet">Browse Album</a> </body></html>
upload.jsp is the download page placed in the jsps directory
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> </head> <body> <h1>Uploading</h1> <form action="<%=request.getContextPath()%>/servlets/UploadServlet" method="post" enctype="multipart/form-data"> File:<input type="file" name="file1"/><br/> Description:<input type="text" name="desc" /><br/> <input type="submit" value="upload" /> </form> </body></html>
Put photos.xml in the src directory
<?xml version="1.0" encoding="UTF-8"?><photos></photos>
Write value object PhotoModel
package cn.hncu.demain;public class PhotoModel { private String id; private String realName; private String ext; private String dir; private String dateTime; private String 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 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 [id=" + id + ", realName=" + realName + ", ext=" + ext + ", dir=" + dir + ", dateTime=" + dateTime + ", ip=" + ip + ", desc=" + desc + "]"; }} There are two types of writing tools:
MyUtil (date formatting, directory breaking code, random id code)
package cn.hncu.utils;import java.text.SimpleDateFormat;import java.util.Date;import java.util.UUID;public class MyUtils { private MyUtils() { } private static SimpleDateFormat format=new SimpleDateFormat("yyyyy year MM month dd day hh:mm:ss"); public static String getCurrentDateTime(){ return format.format(new Date()); } public static String getUUid(){ UUID uuid=UUID.randomUUID(); String id=uuid.toString().replaceAll("-", ""); return id; } public static String getDir(String uuid){ String dir1=Integer.toHexString(uuid.hashCode() & 0xf); String dir2=Integer.toHexString((uuid.hashCode() & 0xf0)>>4); return dir1+"/"+dir2; }}Dom4jFactory (related operations of dom4j, obtain document object, save operation)
package cn.hncu.utils;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.UnsupportedEncodingException;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.io.OutputFormat;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;public class Dom4jFactory { private static Document dom = null; private static String path; static { try { SAXReader sax = new SAXReader(); // Learn how to load the resource path under the server (because our resources have been published from MyEclipse to the Tomcat server, so it is different from the original pure Java project) // Use the current class to find its class loader, and then use the class loader to obtain the resource path path = Dom4jFactory.class.getClassLoader().getResource("photos.xml") .getPath(); dom = sax.read(new FileInputStream(path)); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } public static Document getDom(){ return dom; } public static boolean save(){ try { OutputFormat format=new OutputFormat(); format.setEncoding("utf-8"); XMLWriter w = new XMLWriter( new FileOutputStream(new File(path)),format); w.write(dom); w.close(); return true; } catch (Exception e) { return false; } }}Write PhotoDao from the bottom layer
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.demain.PhotoModel;import cn.hncu.utils.Dom4jFactory;public class PhotoDao { //Add public boolean add(PhotoModel photo){ Document dom=Dom4jFactory.getDom(); Element root=dom.getRootElement(); Element ePhoto=root.addElement("photo"); ePhoto.addAttribute("id", photo.getId()); ePhoto.addAttribute("realName", photo.getRealName()); ePhoto.addAttribute("dir", photo.getDir()); ePhoto.addAttribute("ip", photo.getIp()); ePhoto.addAttribute("dateTime", photo.getDateTime()); ePhoto.addAttribute("ext", photo.getExt()); ePhoto.addElement("desc").setText(photo.getDesc()); boolean boo=Dom4jFactory.save(); return boo; } //Browse public List<PhotoModel> getAll(){ Document dom=Dom4jFactory.getDom(); List<PhotoModel> list=new ArrayList<PhotoModel>(); Element root=dom.getRootElement(); Iterator<Element> it=root.elementIterator(); while(it.hasNext()){ PhotoModel photo=new PhotoModel(); Element e=it.next(); photo.setId(e.attributeValue("id")); photo.setDateTime(e.attributeValue("dateTime")); photo.setDir(e.attributeValue("dir")); photo.setExt(e.attributeValue("ext")); photo.setIp(e.attributeValue("ip")); photo.setRealName(e.attributeValue("realName")); photo.setDesc(e.elementText("desc")); list.add(photo); } return list; } public PhotoModel getSingleById(String id) { Document dom=Dom4jFactory.getDom(); List<PhotoModel> list=getAll(); for(PhotoModel photo:list){ if(photo.getId().equals(id)){ return photo; } } return null; } public boolean del(String id) { Document dom=Dom4jFactory.getDom(); Element e=(Element) dom.selectSingleNode("//photo[@id='"+id.trim()+"']"); return e.getParent().remove(e); }} Write four servlets at the end
UploadServlet Upload Servlet code
package cn.hncu.servlets;import java.io.File;import java.io.IOException;import java.io.InputStream;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 org.apache.commons.io.FileUtils;import cn.hncu.dao.PhotoDao;import cn.hncu.demain.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;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.println("Get upload is not supported!"); 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(); String path=request.getServletContext().getRealPath("/photos"); DiskFileItemFactory factory=new DiskFileItemFactory(); factory.setRepository(new File("g:/a")); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(1024*1024*10);//Maximum 10M upload.setHeaderEncoding("utf-8");//Use to set the encoding of the file name, equivalent to: request.setCharacterEncoding("utf-8"); FileItem fi=null; try { List<FileItem> list=upload.parseRequest(request); PhotoModel photo = new PhotoModel();//Data encapsulation---7 attributes are required boolean boo=false; InputStream in = null; for(FileItem fi2:list){ fi=fi2; if(fi.isFormField()){ String desc=fi.getString("utf-8"); photo.setDesc(desc);//desc }else{ in=fi.getInputStream(); String realName=fi.getName(); if(realName==null || realName.trim().equals("")){ out.print("No file selected!"); return; } if(realName.indexOf("//")!=-1){ realName=realName.substring(realName.lastIndexOf("//")+1); } photo.setRealName(realName);//Real file name String ext=realName.substring(realName.lastIndexOf(".")); photo.setExt(ext);//3 photo.setDateTime(MyUtils.getCurrentDateTime());//4 photo.setId(MyUtils.getUUid());//5 photo.setDir(MyUtils.getDir(photo.getId()));//6 photo.setIp(request.getRemoteAddr());//7 } } //Storage photo information to the database PhotoDao dao=new PhotoDao(); boo=dao.add(photo); //If the above photo information is saved successfully, then you will start to receive the image file and save it to the server hard disk if(boo){ System.out.println(dao); path=path+"/"+photo.getDir(); File dir=new File(path); if(!dir.exists()){ dir.mkdir(); } String fileName=path+"/"+photo.getId()+photo.getExt(); FileUtils.copyInputStreamToFile(in, new File(fileName)); String strPath = request.getContextPath()+"/servlets/ShowServlet"; out.print("Uploaded successfully!<a href='"+strPath+"'>Browse album</a>"); }else{ out.print("Upload failed!"); } } catch (FileUploadException e) { throw new RuntimeException("Upload failed!"); ", e); } finally{ if(fi!=null){ fi.delete(); } } out.flush(); out.close(); }}ShowServlet The Servlet side of browsing albums
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.dao.PhotoDao;import cn.hncu.demain.PhotoModel;public class ShowServlet extends HttpServlet { IOException if an error occurred public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("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>"); String table="<table border='1' width='100%'>"+ "<tr><th>File name</th><th>Upload ip</th><th>Upload time</th><th>Image</th><th>Instructions</th><th>Operation</th></tr>" ; out.print(table); PhotoDao dao=new PhotoDao(); List<PhotoModel> list=dao.getAll(); for(PhotoModel p:list){ out.print("<tr>"); out.println("<td>"+p.getRealName()+"</td>"); out.println("<td>"+p.getIp()+"</td>"); out.println("<td>"+p.getDateTime()+"</td>"); //Output picture String path=request.getContextPath()+"/photos/"+p.getDir()+"/"+p.getId()+p.getExt(); out.println("<td><a href='"+path+"'><img src='"+path+"' width='200' height='200'></img></a></td>"); String op="<a href='"+request.getContextPath()+"/servlets/DelServlet?id="+p.getId()+"'>Delete</a>"; out.println("<td>"+p.getDesc()+"</td>"); op+="<a href='"+request.getContextPath()+"/servlets/DownServlet?id="+p.getId()+"'>Download</a>"; out.println("<td>"+op+"</td>"); out.print("</tr>"); } out.println("</table>"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); }}Server code downloaded by DownServlet
package cn.hncu.servlets;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.PrintWriter;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.dao.PhotoDao;import cn.hncu.demain.PhotoModel;public class DownServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id=request.getParameter("id"); response.setContentType("application/force-download"); PhotoModel p=new PhotoDao().getSingleById(id); if(p!=null){ String realName=p.getRealName(); realName=new String(realName.getBytes("iso8859-1"),"utf-8"); response.setHeader("content-Disposition", "attachment;filename=/""+realName+"/""); String relpath=getServletContext().getRealPath("/photos/"+p.getDir()+"/"+p.getId()+p.getExt()); InputStream in=new FileInputStream(relpath); OutputStream out=response.getOutputStream(); System.out.println(relpath); byte buf[]=new byte[1024]; int len=0; while ((len=in.read(buf))!=-1){ out.write(buf,0,len); } out.close(); }else{ response.setContentType("text/html;charset=utf-8"); response.getWriter().println("This file has been deleted!"); } }}Delservlet Delete Server
package cn.hncu.servlets;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 javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import cn.hncu.dao.PhotoDao;import cn.hncu.demain.PhotoModel;public class DelServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } 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(); String id=request.getParameter("id"); PhotoModel p=new PhotoDao().getSingleById(id); if(p!=null){ if(!p.getIp().equals(request.getRemoteAddr())){ out.println("You do not have permission to delete it! "); return; } //※※※※The following parts are added to the following class!!! //1Delete the information in the database PhotoDao dao=new PhotoDao(); boolean boo=dao.del(id); //2Delete the file in the server hard disk if(boo){ String fileName="photos/"+p.getDir()+"/"+p.getId()+p.getExt(); String pathFileName = getServletContext().getRealPath(fileName); File f=new File(pathFileName); if(f.exists()){ f.delete(); } String strPath = request.getContextPath()+"/servlets/ShowServlet"; out.println("Photo delete successfully! <a href='"+strPath+"'>Browse album</a>"); }else{ out.println("Photo delete failed!"); } }else{ response.setContentType("text/html;charset=utf-8"); response.getWriter().println("This file does not exist!"); } }}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.