index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
My JSP 'index.jsp' starting page
小相册
上传照片
浏览相册
cn.hncu.dao:---这里直接写实现类了,最好是接口+实现类+工厂
PhotoDAO
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.Photo;
import cn.hncu.utils.Dom4jFactory;
public class PhotoDAO {
public boolean save(Photo photo) {
Document dom=Dom4jFactory.getDocument();
Element root=dom.getRootElement();
//给root(photos>添加一个子元素
//值对象-id,realName,dt,ext,ip,dir,desc
Element ePhoto = root.addElement("photo");
ePhoto.addAttribute("id", photo.getId());
ePhoto.addAttribute("realName", photo.getRealName());
ePhoto.addAttribute("dt", photo.getDt());
ePhoto.addAttribute("ext", photo.getExt());
ePhoto.addAttribute("ip", photo.getIp());
ePhoto.addAttribute("dir", photo.getDir());
ePhoto.addElement("desc").setText(photo.getDesc());
//持久化
try {
Dom4jFactory.save();
} catch (Exception e) {
return false;
}
return true;
}
public List getAll() {
List resList=new ArrayList();
Document dom=Dom4jFactory.getDocument();
Element root=dom.getRootElement();
Iterator it = root.elementIterator("photo");
while(it.hasNext()){
Element ePhoto=it.next();
Photo photo=new Photo();
//值对象-id,realName,dt,ext,ip,dir,desc
photo.setId(ePhoto.attributeValue("id"));
photo.setRealName(ePhoto.attributeValue("realName"));
photo.setDt(ePhoto.attributeValue("dt"));
photo.setExt(ePhoto.attributeValue("ext"));
photo.setIp(ePhoto.attributeValue("ip"));
photo.setDir(ePhoto.attributeValue("dir"));
photo.setDesc(ePhoto.elementText("desc"));
resList.add(photo);
}
return resList;
}
public Photo getSingleById(String id) {
List list=getAll();
for(Photo photo:list){
if(photo.getId().equals(id)){
return photo;
}
}
return null;
}
public boolean del(String id) {
Document dom=Dom4jFactory.getDocument();
String xpath="//photo[@id='"+id.trim()+"']";
Element ePhtot = (Element) dom.selectSingleNode(xpath);
boolean boo = ePhtot.getParent().remove(ePhtot);
try {
Dom4jFactory.save();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return boo;
}
}
cn.hncu.domain
Photo
package cn.hncu.domain;
public class Photo {
//id,realName,dt,ext,ip,dir,desc
private String id; //Uuid
private String realName;//文件的真实名
private String dt; //上传相片的日期时间
private String ext; //文件的扩展名
private String ip; //上传文件的用户的ip地址
private String dir; //文件存放目录--打散的
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 getDt() {
return dt;
}
public void setDt(String dt) {
this.dt = dt;
}
public String getExt() {
return ext;
}
public void setExt(String ext) {
this.ext = ext;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Override
public String toString() {
return "Photo [id=" + id + ", realName=" + realName + ", dt=" + dt
+ ", ext=" + ext + ", ip=" + ip + ", dir=" + dir + ", desc="
+ desc + "]";
}
}
photo.xml:
cn.hncu.utils:
Dom4jFactory
package cn.hncu.utils;
import java.io.File;
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.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class Dom4jFactory {
private static Document dom;
private static String path;
static{
SAXReader sax=new SAXReader();
path=Dom4jFactory.class.getClassLoader().getResource("photo.xml").getPath();
File file=new File(path);
try {
dom = sax.read(file);
} catch (DocumentException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
private Dom4jFactory(){
}
public static Document getDocument(){
return dom;
}
public static void save(){
try {
XMLWriter w=new XMLWriter(new FileOutputStream(new File(path)));
w.write(dom);
w.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
MyUtils
package cn.hncu.utils;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
public class MyUtils {
public static String getUuid(){
return UUID.randomUUID().toString().replaceAll("-", "");
}
private static DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static String getCurrentDT(){
return df.format(new Date());
}
public static String getDir(String uuid){
int dir1=uuid.hashCode()&0xf;
int dir2=(uuid.hashCode()&0xf0)>>4;
return dir1+"\\"+dir2;
}
}
cn.hncu.servlet:
ShowServlet
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.PhotoDAO;
import cn.hncu.domain.Photo;
public class ShowServlet 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 {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("");
out.println("");
out.println(" A Servlet ");
out.println(" ");
String sTable=""+
"文件名 上传时间 图片 文字说明 操作 ";
out.println(sTable);
//获取所有相片,每个相片显示成表格的一行
PhotoDAO dao=new PhotoDAO();
List photos = dao.getAll();
for(Photo photo:photos){
out.println("");
out.println(""+photo.getRealName()+" "); //文件名
out.println(""+photo.getDt()+" "); //上传时间
//输出图片--request.getContextPath()
String path=request.getContextPath()+"/"+"photos/"+photo.getDir()+"/"+photo.getId()+photo.getExt();
out.println(" ");
out.println(""+photo.getDesc()+" "); //文字说明
//操作
//通过?id=photo.getId()来传参数
String op="删除 "
+"下载";
out.println(""+op+" ");
out.println(" ");
}
out.println("
");
out.println(" ");
out.println("");
out.flush();
out.close();
}
}
DelServlet
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.PhotoDAO;
import cn.hncu.domain.Photo;
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 {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("");
out.println("");
out.println(" A Servlet ");
out.println(" ");
String id=request.getParameter("id");
String ip=request.getRemoteAddr();
PhotoDAO dao=new PhotoDAO();
Photo photo=dao.getSingleById(id);
if(photo!=null){
//1.判断是否有权删除
if(!photo.getIp().equals(ip)){
out.println("你无权删除别人的图片");
return;
}else{
//2删除数据库中的信息
boolean boo = dao.del(id);
if(boo){
//3.删除服务器磁盘文件
String fileName="photos/"+photo.getDir()+"/"+photo.getId()+photo.getExt();
String realFileName=getServletContext().getRealPath(fileName);
File file=new File(realFileName);
if(file.exists()){
file.delete();
}
//request.getContentType():项目根目录
String strPath=request.getContextPath()+"/ShowServlet";
out.println("相片删除成功! 浏览相册");
}else{
out.println("相片删除失败");
}
}
}else{
out.println("相片已经不存在");
}
out.println(" ");
out.println("");
out.flush();
out.close();
}
}
UploadServlet
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.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.domain.Photo;
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("");
out.println("");
out.println(" A Servlet ");
out.println(" ");
out.println("不支持GET方式");
out.println(" ");
out.println("");
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("");
out.println("");
out.println(" A Servlet ");
out.println(" ");
request.getContentType();
// getServletContext().getRealPath(arg0) 获取路径的绝对地址
// 文件上传核心入口:ServletFileUpload upload=new ServletFileUpload(fileItemFactory);
DiskFileItemFactory fileItemFactory=new DiskFileItemFactory();
fileItemFactory.setRepository(new File("e://a")); //临时文件的存放目录
// DiskFileItemFactory fileItemFactory2=new DiskFileItemFactory();
// ServletFileUpload upload=new ServletFileUpload(fileItemFactory2);
// List list = upload.parseRequest(request);
ServletFileUpload upload=new ServletFileUpload(fileItemFactory);
upload.setSizeMax(1024*1024*10);
// request.setCharacterEncoding("utf-8");//设置上传文件的编码
upload.setHeaderEncoding("utf-8"); //设置文件上传头编码
FileItem fi=null;
InputStream in=null;
try {
List list=upload.parseRequest(request);
Photo photo=new Photo(); //值对象-id,realName,dt,ext,ip,dir,desc
for(FileItem item:list){
fi=item;
if(item.isFormField()){ //是普通表单组件
String desc=item.getString("utf-8");
photo.setDesc(desc); //desc--1
}else{ //file表单组件
in=fi.getInputStream();
String fileName=item.getName();
if(fileName==null && fileName.trim().equals("")){
out.println("没有选择上传文件");
return;
}
String realName=fileName.substring( fileName.lastIndexOf("\\")+1); //去去掉文件目录的文件名
photo.setRealName(realName);//realName--2
String ext=realName.substring(realName.lastIndexOf("."));
photo.setExt(ext); //ext--3
photo.setDt( MyUtils.getCurrentDT());//uuid--4
photo.setIp( request.getRemoteHost() );//ip---5
photo.setId(MyUtils.getUuid());
photo.setDir(MyUtils.getDir(photo.getId()));
}
}
//调用dao层--保存photo-bean
PhotoDAO dao=new PhotoDAO();
//只有在文件存储到xml数据库成功后,才把照片存储到服务器中
//1.把photo值对象包装的数据存储到数据库
boolean boo = dao.save(photo);
if(boo){
//获取文件在服务器中的存储目录
String path=getServletContext().getRealPath("/photos");
path=path+"/"+photo.getDir();
File dir=new File(path);
if(!dir.exists()){
dir.mkdir();
}
//开始存储
String fileName=path+"/"+photo.getId()+photo.getExt(); //存储到服务器磁盘的文件名
//拿到FileItem的in流
// in = fi.getInputStream(); //只有文件表单组件才有这个in流,所以只能在file表单组件中获取
//2.把图片存储到服务器磁盘
//使用FileUtil中的工具吧FileItem流的数据拷贝到File中
FileUtils.copyInputStreamToFile(in, new File(fileName));
out.println("图片上传成功返回主界面");
}else{
out.println("图片上传失败");
}
} catch (FileUploadException e) {
e.printStackTrace();
} finally{
if(fi!=null){
fi.delete(); //删除临时文件
}
}
out.println(" ");
out.println("");
out.flush();
out.close();
}
}
DownServlet
package cn.hncu.servlet;
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.dao.PhotoDAO;
import cn.hncu.domain.Photo;
public class DownServlet extends HttpServlet {
private PhotoDAO dao=new PhotoDAO();
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");
Photo photo=dao.getSingleById(id);
//把服务器磁盘中的相片文件读取出来,写到客户端
if(photo!=null){
String realName=photo.getRealName();
realName=URLEncoder.encode(realName,"utf-8");
//设置下载的响应头
response.setContentType("application/force-download");
response.setHeader("content-Disposition", "attachment;filename='\'"+realName+"\'");
String fileName="/photos/"+photo.getDir()+"/"+photo.getId()+photo.getExt();//相对路径
String pathFileName=getServletContext().getRealPath(fileName); //真正的带盘符的路径
InputStream in=new FileInputStream(pathFileName);
OutputStream out=response.getOutputStream();
byte bs[]=new byte[512];
int len=-1;
while((len=in.read(bs))!=-1){
out.write(bs, 0, len);
}
in.close();
out.close();
}
}
}