一.用mysql建立数据库及其表
create database file set gbk;
create table user(id int not null primary key auto_increment,username varchar(20),password varchar(20));
create table file(fileid int not null primary key auto_increment,filesavename varchar(100),filename varchar(100),filetype varchar(100),filesize varchar(50),fileinfo text,fileuptime varchar(30),fileip varchar(30),filetimes varchar(30),filetag varchar(30));
二.源码实例
1.表现层页面
(1)login.jsp(登录页面)
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <% String path = request.getContextPath(); %>
(2)index.jsp(首页)
<%@ page language="java" pageEncoding="gbk" isELIgnored="false"%> <%@page import="bean.FileInfo"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%> <% String path = request.getContextPath(); %>
(3)uploadfile.jsp(文件上传页面)
<%@ page contentType="text/html;charset=gbk" pageEncoding="gbk"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"prefix="c"%>
<%@ page isELIgnored="false"%>
(4)fileinfo.jsp(文件信息预览页面)
<%@ page language="java"pageEncoding="gbk" isELIgnored="false"%> <% String path = request.getContextPath(); %>
(5)zxc.js
function alertWin(title, msg, w, h){ var titleheight = "20px"; var bordercolor = "#666699"; var titlecolor = "#FFFFFF"; var titlebgcolor = "#1d5798"; var bgcolor = "#FFFFFF"; var iWidth = document.documentElement.clientWidth; var iHeight = document.documentElement.clientHeight; var bgObj = document.createElement("div"); bgObj.style.cssText = "position:absolute;left:0px;top:0px;width:"+iWidth+"px;height:"+Math.max(document.body.clientHeight, iHeight)+"px;filter:Alpha(Opacity=10);opacity:0.1;background-color:#000000;z-index:101;"; document.body.appendChild(bgObj); var msgObj=document.createElement("div"); msgObj.style.cssText = "position:absolute;font:11px '宋体';top:"+(iHeight-h)/2+"px;left:"+(iWidth-w) /2+"px;width:"+w+"px;height:"+h+"px;text-align:center;border:1px solid "+bordercolor+";background-color:"+bgcolor+";padding:1px;line-height:22px;z-index:102;"; document.body.appendChild(msgObj); var table = document.createElement("table"); msgObj.appendChild(table); table.style.cssText = "margin:0px;border:0px;padding:0px;"; table.cellSpacing = 0; var tr = table.insertRow(-1); var titleBar = tr.insertCell(-1); titleBar.style.cssText = "width:100%;height:"+titleheight+"px;text-align:left;padding:3px;margin:0px;font:bold 13px '宋体';color:"+titlecolor+";border:1px solid " + bordercolor + ";cursor:move;background-color:" + titlebgcolor; titleBar.style.paddingLeft = "10px"; titleBar.innerHTML = title; var moveX = 0; var moveY = 0; var moveTop = 0; var moveLeft = 0; var moveable = false; var docMouseMoveEvent = document.onmousemove; var docMouseUpEvent = document.onmouseup; titleBar.onmousedown = function() { var evt = getEvent(); moveable = true; moveX = evt.clientX; moveY = evt.clientY; moveTop = parseInt(msgObj.style.top); moveLeft = parseInt(msgObj.style.left); document.onmousemove = function() { if (moveable) { var evt = getEvent(); var x = moveLeft + evt.clientX - moveX; var y = moveTop + evt.clientY - moveY; if ( x > 0 &&( x + w < iWidth) && y > 0 && (y + h < iHeight) ) { msgObj.style.left = x + "px"; msgObj.style.top = y + "px"; } } }; document.onmouseup = function () { if (moveable) { document.onmousemove = docMouseMoveEvent; document.onmouseup = docMouseUpEvent; moveable = false; moveX = 0; moveY = 0; moveTop = 0; moveLeft = 0; } }; } var closeBtn = tr.insertCell(-1); closeBtn.style.cssText = "cursor:pointer; padding:2px;background-color:" + titlebgcolor; closeBtn.innerHTML = "x"; closeBtn.onclick = function(){ document.body.removeChild(bgObj); document.body.removeChild(msgObj); } var msgBox = table.insertRow(-1).insertCell(-1); msgBox.style.cssText = "font:10pt '瀹嬩綋';"; msgBox.colSpan = 2; msgBox.innerHTML = document.getElementById("logincontent").innerHTML; function getEvent() { return window.event || arguments.callee.caller.arguments[0]; } } function $(id){ return document.getElementById(id); } function refresh(){ $("imgCode").src="<%=path%>/servlet/textBufferedImage?timestampt="+new Date().getTime(); alert($("imgCode").src); } function del(name){ if(confirm("你确定要删除该文件吗?")){ window.location.href=$("path").value+"/fileUpDownLoad.do?method=deleteFile&filesavename="+name; } } function query(){ window.location.href=$("path").value+"/fileUpDownLoad.do?method=getFileList"; } function download(name){ var url=$("path").value+"/fileUpDownLoad.do?method=downloadFile&downfilename="+name; window.location.href=url; } window.οnlοad=function(){ var tab= document.getElementById("me"); var trs=tab.getElementsByTagName("tr"); for(var i=0;i
2.公用类和javabean
(1)DBAccess.java(数据库连接)
package bean; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DBAccess { /** * @param args */ public DBAccess(){ } public static Connection getConnection(){ try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block System.out.println("驱动程序未找!"); e.printStackTrace(); } String url="jdbc:mysql://localhost:3306/file?characterEncoding=gbk"; String user="root"; String password="123"; Connection conn=null; try { conn=DriverManager.getConnection(url, user, password); } catch (SQLException e) { // TODO Auto-generated catch block System.out.println("数据库连接出错啦!"); e.printStackTrace(); } System.out.println("Connection连接成功!"); return conn; } public static void main(String[] args) { // TODO Auto-generated method stub Connection connection=getConnection(); } }
(2)FileInfo.java(文件信息bean)
package bean; public class FileInfo implements java.io.Serializable { // Fields private String fileId; private String fileSavename; private String fileName; private String fileType; private String fileSize; private String fileInfo; private String fileUptime; private String fileIp; private long fileTimes; private String fileTag; /** default constructor */ public FileInfo() { } /** minimal constructor */ public FileInfo(String fileId) { this.fileId = fileId; } /** full constructor */ public FileInfo(String fileId, String fileSavename, String fileName, String fileType, String fileSize, String fileInfo, String fileUptime, String fileIp,long fileTimes,String fileTag) { this.fileId = fileId; this.fileSavename = fileSavename; this.fileName = fileName; this.fileType = fileType; this.fileSize = fileSize; this.fileInfo = fileInfo; this.fileUptime = fileUptime; this.fileIp = fileIp; this.fileTimes=fileTimes; this.fileTag=fileTag; } // Property accessors public String getFileId() { return this.fileId; } public void setFileId(String fileId) { this.fileId = fileId; } public String getFileSavename() { return this.fileSavename; } public void setFileSavename(String fileSavename) { this.fileSavename = fileSavename; } public String getFileName() { return this.fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getFileType() { return this.fileType; } public void setFileType(String fileType) { this.fileType = fileType; } public String getFileSize() { return this.fileSize; } public void setFileSize(String fileSize) { this.fileSize = fileSize; } public String getFileInfo() { return this.fileInfo; } public void setFileInfo(String fileInfo) { this.fileInfo = fileInfo; } public String getFileUptime() { return this.fileUptime; } public void setFileUptime(String fileUptime) { this.fileUptime = fileUptime; } public String getFileIp() { return this.fileIp; } public void setFileIp(String fileIp) { this.fileIp = fileIp; } public void setFileTimes(long fileTimes) { this.fileTimes = fileTimes; } public long getFileTimes() { return fileTimes; } public void setFileTag(String fileTag) { this.fileTag = fileTag; } public String getFileTag() { return fileTag; } }
(3)PageListData.java(分页参数分装bean)
package bean; import java.util.ArrayList; import java.util.List; import java.util.Locale; import javax.servlet.http.HttpServletRequest; public class PageListData { // 分页结果集 private List dataArray = null; // 记录总数 private int count = 0; // 每页显示记录数 private int pageSize = 0; // 当前页数 private int page = 1; public PageListData() { } public List getDataArray() { return dataArray; } public void setDataArray(List dataArray) { this.dataArray = dataArray; } // 记录总数 public int getCount() { return count; } public void setCount(int count) { this.count = count; } // 总页数 public int getPageCount() { if(count%pageSize==0){ return count/pageSize; }else{ return count/pageSize+1; } } // 每页显示 录数 public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } // 当前页数 public int getPage() { return page; } public void setPage(int page) { this.page = page; } /** * 封装分页栏函数 必需被包含在某个Form之中 * @param request HttpServletRequest * @return String pages 当前页号 pageSize 每页显示行数 */ public String getFooter(HttpServletRequest request) { String previous = "上一页"; String next ="下一页"; StringBuffer pageStr = new StringBuffer(""); pageStr.append("
"); int nTotalPages = getPageCount(); //总页数 int nCurrentPage = getPage(); //当前页 int nPrevPage = getPage() - 1; //上一页 int nNextPage = getPage() + 1; //下一页 int first = 0; int last = 0; if (nCurrentPage > 1){ pageStr.append("" + previous +" "); } for (int i = 1; i <= nTotalPages; i++) { if (i == nCurrentPage){ pageStr.append("" + i + " "); } else { if(nCurrentPage == 1 && (i == 2 || i==3)) { pageStr.append("" + i + " "); } else if (i != 1 && nCurrentPage >= 5 && i < nCurrentPage) { if(first == 0) { pageStr.append("..."); first = 1; } if(nCurrentPage == nTotalPages && i == nTotalPages - 1) { pageStr.append("" + i + " "); } } else if( i <= nTotalPages && nCurrentPage <= nTotalPages - 4 && i > (nCurrentPage + 1)) { if(last == 0) { pageStr.append("..."); last = 1; } if(i==nTotalPages){ pageStr.append("" + i + " "); } } else { pageStr.append("" + i + " "); } } } if (nCurrentPage < nTotalPages) { pageStr.append("" + next +"
"); int totalPages = getPageCount(); //总页数 int currentPage = getPage(); //当前页 int totalcount=getCount();//总记录数 int prevPage = getPage() - 1; //上一页 int nextPage = getPage() + 1; //下一页 pageStr.append("共有"+totalcount+"条记录 "); pageStr.append("第"+currentPage+"页/共"+totalPages+"页 "); if(currentPage>1) pageStr.append("首页 "); if(currentPage==1) pageStr.append("首页 "); if(currentPage>1) pageStr.append("上一页 "); if(currentPage<=1) pageStr.append("上一页 "); if(currentPage
(4)StringHandler.java(字符串处理)
package bean; import java.text.SimpleDateFormat; import java.util.Date; public class StringHandler { public static String timeTostr(Date date){ String strDate=""; SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); strDate=format.format(date); return strDate; } public static String getSerial(Date date,int index){ long msel=date.getTime(); //��ȡ������ SimpleDateFormat fm=new SimpleDateFormat("MMddyyyyHHmmssSS"); //����ת������ msel+=index; //ͨ��һ��ֵ�ı������ date.setTime(msel); //ͨ��ı��ĺ����������������� String serials=fm.format(date); //ת������ʱ�������Ϊ��MMddyyyyHHmmssSS����ʽ return serials; } public static String changehtml(String str){ String change=""; if(str!=null&&!str.equals("")){ change=str.replace("&","&"); change=change.replace(" "," "); change=change.replace("<","<"); change=change.replace(">",">"); change=change.replace("/"","""); change=change.replace("/r/n","
"); } return change; } }
(5)User.java
package bean; public class User { private int id; private String username; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
(6)TextBufferedImage.java(验证码servlet)
package servlet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import java.util.Random; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder; public class TextBufferedImage extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { //产生随机密码 resp.setHeader("Cache-Control","no-cache"); HttpSession session = req.getSession(); String randomPassword = getRandom(4); System.out.println("randomPassword="+randomPassword); session.setAttribute("randomCode", randomPassword); OutputStream out = resp.getOutputStream(); try { JPEGImageEncoder encode = JPEGCodec.createJPEGEncoder(out); BufferedImage bi = CreateBufferedImage(randomPassword); encode.encode(bi); } catch (Exception e) { e.printStackTrace(); } } /** * 把随机码写到图片上返回 * * @param randomPassword //随机码 * @return */ private BufferedImage CreateBufferedImage(String randomPassword) { int width = 80; int height = 20; BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = bufferedImage.createGraphics(); g2d.clearRect(0, 0, width, height); // 设定背景色 g2d.setColor(getRandColor(200,250)); g2d.fillRect(0, 0, width, height); // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到 Random random = new Random(); g2d.setColor(getRandColor(160,200)); g2d.setFont(getFont()); for (int i=0;i<155;i++) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); g2d.drawLine(x,y,x+xl,y+yl); } // 取随机产生的认证码(4位数字) String sRand=""; for (int i=0;i<4;i++){ String rand = randomPassword.substring(i, i+1); sRand+=rand; // 将认证码显示到图象中 g2d.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成 g2d.drawString(rand,14*i+12,17); } g2d.dispose(); return bufferedImage; } private Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色 Random random = new Random(); if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } private Font getFont() { Random random = new Random(); Font font[] = new Font[5]; font[0] = new Font("Ravie", Font.PLAIN, 20); font[1] = new Font("Antique Olive Compact", Font.PLAIN, 20); font[2] = new Font("Forte", Font.PLAIN, 20); font[3] = new Font("Wide Latin", Font.PLAIN, 20); font[4] = new Font("Gill Sans Ultra Bold", Font.PLAIN, 20); return font[random.nextInt(5)]; } /** * 产生随机码(字母+数字) * * @param length * 随机码长度 * @return 随机码 */ private String getRandom(int length) { String randomCode = ""; for (int i = 0; i < length; i++) { randomCode += getRandChar(); } return randomCode; } public String getRandChar() { int rand = (int) Math.round(Math.random() * 2); long itmp = 0; char ctmp = '/u0000'; // 根据rand的值来决定来生成一个大写字母、小写字母和数字 switch (rand) { // 生成大写字母 case 1: itmp = Math.round(Math.random() * 25 + 65); ctmp = (char) itmp; return String.valueOf(ctmp); // 生成小写字母 case 2: itmp = Math.round(Math.random() * 25 + 97); ctmp = (char) itmp; return String.valueOf(ctmp); // 生成数字 default: itmp = Math.round(Math.random() * 9); return String.valueOf(itmp); } } }
3.数据层
(1)UserDAO.java
package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import bean.DBAccess; import bean.User; public class UserDAO { public User checkLogin(String username, String password) { String sql = "select * from user where username=? and password=?"; PreparedStatement ps = null; ResultSet rs = null; Connection conn = null; User user=null; try { conn = DBAccess.getConnection(); ps = conn.prepareStatement(sql); ps.setString(1, username); ps.setString(2, password); rs = ps.executeQuery(); if (rs.next()) { if (rs.getString("username").equals(username) && rs.getString("password").equals(password)) { user=new User(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); } } rs.close(); ps.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } return user; } }
(2)FileDAO.java
package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import bean.DBAccess; import bean.FileInfo; public class FileDAO { DBAccess db = new DBAccess(); public boolean isExsitSameFileName(String filename, HttpServletRequest request) { boolean flag = false; PreparedStatement ps = null; ResultSet rs = null; Connection connection = db.getConnection(); String sql = "select * from file where filename=?"; try { ps = connection.prepareStatement(sql); ps.setString(1, filename); rs = ps.executeQuery(); if (rs.next()) { FileInfo fileInfo = new FileInfo(); fileInfo.setFileId(rs.getString("fileid")); fileInfo.setFileInfo(rs.getString("fileinfo")); fileInfo.setFileIp(rs.getString("fileip")); fileInfo.setFileName(rs.getString("filename")); fileInfo.setFileSavename(rs.getString("filesavename")); fileInfo.setFileSize((rs .getString("filesize"))); fileInfo.setFileTag(rs.getString("filetag")); fileInfo.setFileTimes(Integer.parseInt(rs .getString("filetimes"))); fileInfo.setFileType(rs.getString("filetype")); fileInfo.setFileUptime(rs.getString("fileuptime")); java.io.File f = new java.io.File(request.getSession() .getServletContext().getRealPath("/") + fileInfo.getFileSavename()); if (f.isFile()) flag = true; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (ps != null) ps.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } } return flag; } public boolean saveFile(FileInfo fileInfo) { boolean flag = false; PreparedStatement ps = null; Connection connection = db.getConnection(); String sql = "insert into file(fileId,fileSavename,fileName,fileType,fileSize,fileInfo,fileUptime,fileIp,fileTimes,fileTag) " + "values(?,?,?,?,?,?,?,?,?,?)"; try { ps = connection.prepareStatement(sql); ps.setString(1, fileInfo.getFileId()); ps.setString(2, fileInfo.getFileSavename()); ps.setString(3, fileInfo.getFileName()); ps.setString(4, fileInfo.getFileType()); ps.setString(5, String.valueOf(fileInfo.getFileSize())); String fileString = fileInfo.getFileInfo(); // fileString.replaceAll("/n", "").replaceAll("@", ""); ps.setString(6, fileString); ps.setString(7, fileInfo.getFileUptime()); ps.setString(8, fileInfo.getFileIp()); ps.setString(9, String.valueOf(fileInfo.getFileTimes())); ps.setString(10, fileInfo.getFileTag()); int i = ps.executeUpdate(); if (i == 1) flag = true; } catch (Exception e) { e.printStackTrace(); } finally { try { ps.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } } return flag; } public Map queryFile(HttpServletRequest request,int currentPage,int pageSize) { boolean flag = false; Map map=new HashMap(); PreparedStatement ps = null; PreparedStatement ps1 = null; PreparedStatement ps2=null; ResultSet rs = null; ResultSet rs2=null; int totalcount=0; List list = new ArrayList
"); } buffer.append(str.substring(i * len)); } else { for (; i < forEach; i++) { if (i < forEach - 1) { buffer.append(str.substring(i * len, (i + 1) * len)) .append("
"); } else { buffer.append(str.substring(i * len)).append("
"); } } } return buffer.toString(); } public static String formatFileSize(Double size){ String result=""; int flag=(int)(size/1024); int remain=(int)(size%1024); if(flag<1) result=new java.text.DecimalFormat("#.00").format(size)+" KB"; else if(flag==1) result="1 M"; else{ if(remain==0) result=flag+" M"; else result=new java.text.DecimalFormat("#.00").format(size/1024)+" M"; } return result; } }
4.业务逻辑层
(1)LoginAction.java
/* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */ package com.zxc.struts.action; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import bean.User; import dao.UserDAO; public class LoginAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException { // TODO Auto-generated method stub String username = request.getParameter("username"); String password = request.getParameter("password"); String randomCode = request.getSession().getAttribute("randomCode") == null ? "" : request.getSession().getAttribute("randomCode").toString(); String randomCodePage = request.getParameter("randcode") == null ? "" : request.getParameter("randcode"); String forward = ""; if (randomCode.equalsIgnoreCase((randomCodePage.trim()))) { User user = new UserDAO().checkLogin(username, password); if (user != null) { request.getSession().setAttribute("user", user); return new ActionForward("/fileUpDownLoad.do?method=getFileList"); } else { return mapping.findForward("failure"); } } else { return mapping.findForward("failure"); } } }
(2)FileUpDownLoadAction.java
/* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */ package com.zxc.struts.action; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.actions.DispatchAction; import bean.FileInfo; import bean.PageListData; import bean.StringHandler; import com.jspsmart.upload.File; import com.jspsmart.upload.Files; import com.jspsmart.upload.SmartUpload; import com.jspsmart.upload.SmartUploadException; import dao.FileDAO; /** * MyEclipse Struts Creation date: 01-12-2010 * * XDoclet definition: * * @struts.action parameter="method" */ public class FileUpDownLoadAction extends DispatchAction { private FileDAO service = new FileDAO(); ActionMessages messages = new ActionMessages(); /** * Method execute * * @param mapping * @param form * @param request * @param response * @return ActionForward */ // 文件上传 public ActionForward uploadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { // TODO Auto-generated method stub String message = ""; long maxsize = 1024 * 1024 * 10; String filedir = request.getSession().getServletContext().getRealPath( "/"); System.out.println("filedir" + filedir); try { SmartUpload myup = new SmartUpload(); myup.initialize(this.getServlet(), request, response); myup.setAllowedFilesList("pdf,doc,txt,rar,jar"); myup.setTotalMaxFileSize(maxsize); myup.upload(); Files files = myup.getFiles(); int count = files.getCount(); Date date = new Date(); // String path = request.getContextPath(); for (int i = 0; i < count; i++) { com.jspsmart.upload.File file = files.getFile(i); if (!file.isMissing()) { if (service .isExsitSameFileName(file.getFileName(), request)) { System.out.println(file.getFileName()); message = "" + "您上传的文件<" + file.getFileName() + ">名已经存在,请重新选择!"; } else { int filesize = file.getSize() / 1024; if (filesize == 0) { message = "" + "文件<" + file.getFileName() + ">是0字节的文件,请上传非空文件!"; } else if (filesize > 1024 * 20) { message = "" + "文件<" + file.getFileName() + ">已经超过20兆了,请上传小于20兆的文件!"; } else { String filename = file.getFileName(); String filetype = file.getContentType().trim(); String savename = StringHandler.getSerial(date, i) + "." + file.getFileExt(); String fileinfo = myup.getRequest().getParameter( "fileinfo" + (i + 1)); System.out.println(fileinfo); String filetag = myup.getRequest().getParameter( "tag" + (i + 1)); String uptime = StringHandler.timeTostr(date); FileInfo filebean = new FileInfo(); filebean.setFileName(filename); filebean.setFileSavename(savename); filebean.setFileType(filetype); filebean.setFileSize(String.valueOf(filesize)); filebean.setFileInfo(fileinfo); filebean.setFileUptime(uptime); filebean.setFileTag(filetag); // filebean.setFileTimes(filetimes); String IP = request.getRemoteAddr(); String originIP = request .getHeader("x-forwarded-for"); if (originIP == null || originIP.length() == 0) { filebean.setFileIp(IP); } else { filebean.setFileIp(originIP); } String savepath = filedir + savename; java.io.File f = new java.io.File(filedir); if (!f.exists()) f.mkdirs(); file.saveAs(savepath, File.SAVEAS_AUTO); if (service.saveFile(filebean)) { message += "" + "文件 " + file.getFilePathName() + " 上传成功!
"; } else { message += "上传失败!"; } } } } } } catch (java.lang.SecurityException e1) { if(e1.getMessage().startsWith("Total File")){ message="●您上传的文件太大!" ; }else{ message = "●上传的文件格式错误,只能上传格式为pdf,doc,txt,rar和jar类型的文件!"; } e1.printStackTrace(); } catch (Exception e2) { System.out.println("文件上传失败!"); e2.printStackTrace(); } catch (java.lang.OutOfMemoryError e3) { message = "●您上传的文件太大!"; e3.printStackTrace(); } request.setAttribute("message", message); return mapping.findForward("success"); } // 获取文件列表 public ActionForward getFileList(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { int currPage = request.getParameter("pages")==null?1:Integer.parseInt(request.getParameter("pages")); int pageSize = request.getParameter("pageSize")==null?10:Integer.parseInt(request.getParameter("pageSize")); Map map = service.queryFile(request,currPage,pageSize); List list=new ArrayList(); int totalcount=0; if(map!=null){ list=(ArrayList)map.get("resultList"); totalcount=map.get("totalcount")==null?0:(Integer)map.get("totalcount"); } if (list != null && !list.isEmpty()) { PageListData pageListData = new PageListData(); pageListData.setCount(totalcount); pageListData.setPage(currPage); pageListData.setPageSize(pageSize); pageListData.setDataArray(list); request.setAttribute("footer", pageListData.getFooter1(request)); request.setAttribute("pageList", pageListData); return mapping.findForward("list"); } else { String message = "没有文件可以显示!"; request.setAttribute("message", message); return mapping.findForward("list"); } } // 文件下载 public ActionForward downloadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { String downfilename = request.getParameter("downfilename"); FileInfo file = service.findFileByName(downfilename); String filedir = request.getSession().getServletContext().getRealPath( "/"); if (file != null) { SmartUpload mydown = new SmartUpload(); try { mydown.initialize(this.getServlet(), request, response); mydown.setContentDisposition(null); mydown.downloadFile(filedir + downfilename, file.getFileType(), file.getFileName()); service.addUpTimes(file.getFileTimes(), file.getFileSavename()); } catch (ServletException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SmartUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } else { String message = "下载文件出错啦!"; request.setAttribute("message", message); return mapping.findForward("show"); } } // 删除文件 public ActionForward deleteFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { String filesavename = request.getParameter("filesavename"); FileInfo file = service.findFileByName(filesavename); java.io.File f = new java.io.File(request.getSession() .getServletContext().getRealPath("/") + file.getFileSavename()); if (service.deleteFile(filesavename)) { boolean flag = f.delete(); if (flag) { String message = "
5.过滤器
(1)EncodingFilter.java(处理字符编码)
package filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class EncodingFilter implements Filter { protected FilterConfig config; protected String Encoding = null; public void init(FilterConfig config) throws ServletException { this.config = config; this.Encoding = config.getInitParameter("Encoding"); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request.getCharacterEncoding() == null) { if (Encoding != null) { request.setCharacterEncoding(Encoding); response.setCharacterEncoding(Encoding); } } chain.doFilter(request, response); } public void destroy() { } }
(2)UserLoginFilter.java(session过滤器)
package filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class UserLoginFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; String requesturi = httpServletRequest.getRequestURI(); HttpSession session = httpServletRequest.getSession(); Object currentUser = session.getAttribute("user"); if (currentUser == null && !requesturi.endsWith("/login.do") && !requesturi.endsWith("/logout.do") && !requesturi.endsWith("/login.jsp") && !requesturi.endsWith(httpServletRequest.getContextPath() + "/") ) { httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login.jsp"); return; } chain.doFilter(request, response); } public void init(FilterConfig filterConfig) throws ServletException { } }
6.配置文件
(1)struts-config.properties
(2)web.xml
三.运行效果图:
(1)登录
(2)首页
(3)文件上传页面
备注:此工程压缩包我已上传csdn,有兴趣的话可搜索updownload去下载