遍历上传目录下的所有文件显示给用户,并允许用户完成下载。
(读取某一个文件夹下的所有的文件,存到集合里面List,再存到request作用域范围中)。
一个表的相关字段:
CREATETABLE `upfile` (
`id` varchar(50) NOT NULL,
`uuidname` varchar(255) NOT NULL,
`realname` varchar(255) NOT NULL,
`savepath` varchar(255) NOT NULL,
`uptime` datetime NOT NULL,
`description` varchar(255) DEFAULT NULL,
`username` varchar(40) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULTCHARSET=utf8;
一个实体类:
publicclass UploadFile { privateString id ; private String uuidname ; private String realname; private String savepath ; private Date uptime ; private String description ; private String username ; public String getId() { returnid; } publicvoid setId(String id) { this.id = id; } public StringgetUuidname() { returnuuidname; } publicvoid setUuidname(String uuidname) { this.uuidname = uuidname; } public StringgetRealname() { returnrealname; } publicvoid setRealname(String realname) { this.realname = realname; } public StringgetSavepath() { returnsavepath; } publicvoid setSavepath(String savepath) { this.savepath = savepath; } public Date getUptime(){ returnuptime; } publicvoid setUptime(Date uptime) { this.uptime = uptime; } public StringgetDescription() { returndescription; } publicvoid setDescription(String description) { this.description = description; } public StringgetUsername() { returnusername; } publicvoid setUsername(String username) { this.username = username; } }
一个dao接口:
public interface UploadFileDao { publicvoid insert(UploadFile f); public UploadFilegetUploadFile(String id); publicList<UploadFile> getUploadFiles(); }
该接口的实现类:
publicclass UploadFileDaoImpl implements UploadFileDao{ @Override public UploadFilegetUploadFile(String id) { QueryRunner qr = new QueryRunner(DBManager.getDataSource()); String sql = "selectid,uuidname,realname,savepath,uptime,description,username from uploadfile where id=?"; try { UploadFile uf = qr.query(sql,id,new BeanHandler(UploadFile.class)); return uf; } catch(SQLException e) { thrownew RuntimeException(e); } } @Override publicList<UploadFile> getUploadFiles() { QueryRunner qr = new QueryRunner(DBManager.getDataSource()); String sql = "selectid,uuidname,realname,savepath,uptime,description,username from uploadfile order by uptime desc"; try { List<UploadFile> list = qr.query(sql,new BeanListHandler(UploadFile.class)); return list; } catch(SQLException e) { thrownew RuntimeException(e); } } @Override publicvoid insert(UploadFile f) { QueryRunner qr = new QueryRunner(DBManager.getDataSource()); String sql = "insert into uploadfile(id,uuidname,realname,savepath,uptime,description,username)value(?,?,?,?,?,?,?)"; Object []obj={f.getId(),f.getUuidname(),f.getRealname(),f.getSavepath(),f.getUptime(),f.getDescription(),f.getUsername()}; try { qr.update(sql,obj); } catch(SQLException e) { thrownew RuntimeException(e); } } }
服务层的接口和实现类:
import java.util.List; importwww.hbsi.domain.UploadFile; public interfaceBusinessServiceDao { public voidinsert(UploadFile f); public UploadFilegetUploadFile(String id); publicList<UploadFile> getUploadFiles(); }
实现类:
publicclass BusinessServiceDaoImpl implements BusinessServiceDao{ UploadFileDao ufd = new UploadFileDaoImpl(); @Override public UploadFilegetUploadFile(String id) { returnufd.getUploadFile(id); } @Override publicList<UploadFile> getUploadFiles() { returnufd.getUploadFiles(); } @Override publicvoid insert(UploadFile f) { ufd.insert(f); } }
DownLoadServlet类:
publicclass DownLoadServletextends HttpServlet { publicvoid doGet(HttpServletRequest request, HttpServletResponseresponse) throwsServletException, IOException { UploadFile fu; String id = request.getParameter("id"); BusinessServiceDao bsd =new BusinessServiceDaoImpl(); try{ fu = bsd.getUploadFile(id); }catch(Exception e){ request.setAttribute("message", "下载的资源不存在!"); request.getRequestDispatcher("/WEB-INF/manager/message.jsp").forward(request, response); return; } String filename =fu.getSavepath()+fu.getRealname(); // 这句话必须得加且放在流关闭之前 response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(fu.getRealname(),"utf-8")); FileInputStream fis = new FileInputStream(newFile(filename)); OutputStream os = response.getOutputStream(); byte [] buf= newbyte[1024]; int len=0; while((len=fis.read(buf))>0){ os.write(buf, 0, len); } os.close(); fis.close(); } publicvoid doPost(HttpServletRequest request, HttpServletResponseresponse) throwsServletException, IOException { doGet(request, response); } }
ShowAllUploadFiles类:
publicclass ShowAllUploadFilesextends HttpServlet { publicvoid doGet(HttpServletRequest request, HttpServletResponseresponse) throwsServletException, IOException { BusinessServiceDao bsd =new BusinessServiceDaoImpl(); List<UploadFile> list = bsd.getUploadFiles(); request.setAttribute("list", list); request.getRequestDispatcher("/WEB-INF/manager/showfiles.jsp").forward(request, response); } publicvoid doPost(HttpServletRequest request, HttpServletResponseresponse) throwsServletException, IOException { doGet(request, response); } }
UDJumpServlet类:
publicclass UDJumpServletextends HttpServlet { publicvoid doGet(HttpServletRequest request, HttpServletResponseresponse) throwsServletException, IOException { request.getRequestDispatcher("WEB-INF/manager/ud.jsp").forward(request, response); } publicvoid doPost(HttpServletRequest request, HttpServletResponseresponse) throwsServletException, IOException { doGet(request, response); } }
UploadJumpServlet类:
publicclass UploadJumpServletextends HttpServlet { publicvoid doGet(HttpServletRequest request, HttpServletResponseresponse) throwsServletException, IOException { request.getRequestDispatcher("/WEB-INF/manager/upload.jsp").forward(request, response); } publicvoid doPost(HttpServletRequest request, HttpServletResponseresponse) throwsServletException, IOException { doGet(request, response); } }
publicclass UploadServletextends HttpServlet { publicvoid doGet(HttpServletRequest request, HttpServletResponseresponse) throwsServletException, IOException { UploadFile uf=null; String rootPath=this.getServletContext().getRealPath("/WEB-INF/upload"); try { uf = DBUpload.doUpload(request,rootPath,UploadFile.class); }catch (Exception e) { request.setAttribute("message", "文件上传失败!"); request.getRequestDispatcher("/WEB-INF/manager/message.jsp").forward(request, response); e.printStackTrace(); return; } try{ BusinessServiceDao bsd = newBusinessServiceDaoImpl(); bsd.insert(uf); request.setAttribute("message", "文件上传成功!"); }catch(Exception e){ request.setAttribute("message", "文件上传成功但保存失败!"); } request.getRequestDispatcher("/WEB-INF/manager/message.jsp").forward(request,response ); } publicvoid doPost(HttpServletRequest request, HttpServletResponseresponse) throwsServletException, IOException { doGet(request, response); } }
工具类:
获取连接:
publicclass DBManager { staticComboPooledDataSource cpds; static { cpds= new ComboPooledDataSource("mysql"); } publicstatic DataSource getDataSource(){ returncpds; } }
实现文件上传:
publicclass DBUpload { publicstatic <T> UploadFile doUpload(HttpServletRequestrequest,String rootPath,Class<T>clazz) throwsException{ UploadFile uf = (UploadFile) clazz.newInstance(); DiskFileItemFactory factory=new DiskFileItemFactory(); String tempPath=request.getSession().getServletContext().getRealPath("/temp"); factory.setRepository(new File(tempPath)); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("utf-8"); List<FileItem> list= upload.parseRequest(request); for(FileItem item:list){ if(item.isFormField()){ String filename = item.getFieldName(); String filevalue = item.getString(); BeanUtils.setProperty(uf, filename, filevalue); }else{ String filename =item.getName(); String realname = filename.substring(filename.lastIndexOf("\\")+1); String uuidname = getUUID(realname); String savepath=getBranchFolders(realname,rootPath); uf.setRealname(realname); uf.setUuidname(uuidname); uf.setSavepath(savepath); uf.setId(UUID.randomUUID().toString()); uf.setUptime(new Date()); InputStream is = item.getInputStream(); FileOutputStream fos = new FileOutputStream(newFile(savepath+realname)); int len=0; byte buf [] = newbyte[1024]; while((len=is.read(buf))>0){ fos.write(buf, 0, len); } fos.close(); is.close(); item.delete(); } } return uf; } privatestatic String getBranchFolders(String realname, StringrootPath) { intf1=realname.hashCode()&4; intf2=(realname.hashCode()&4)>>4; String savePath=rootPath+"\\"+f1+"\\"+f2+"\\"; File file = newFile(savePath); if(!file.exists()){ file.mkdirs(); } returnsavePath; } privatestatic String getUUID(String realname) { Stringext=realname.substring(realname.lastIndexOf(".")+1); return UUID.randomUUID().toString()+ext; } }
Web层:
index.jsp <html> <frameset rows="20%,*"> <frame name="head" src="UDJumpServlet"> <frame name="body" src=""> </frameset> </html>
message.jsp <html> <body> ${message} </body> </html>
showfiles.jsp <html> <body> <table border ="1px" width="50%" align="center"> <CAPTION>文件下载区</CAPTION> <thead> <th>文件名</th> <th>上传者</th> <th>上传时间</th> <th>文件描述</th> <th>操作</th> </thead> <tbody> <c:forEach var ="file"items="${list}"> <c:url var="url" value="DownLoadServlet"> <c:param name="id"value="${file.id}"/> </c:url> <tr><td>${file.realname}</td> <td>${file.username}</td> <td>${file.uptime}</td> <td>${file.description}</td> <td><a href = "${url}">下载</a></td> </tr> </c:forEach> </tbody> </table> </body> </html>
ud.jsp <html> <body> <h2 align="center">文件上传与下载</h2> <table align="center"> <tr><td><a href="UploadJumpServlet" target="body">上传</a></td><td></td><td></td><td><a href="ShowAllUploadFiles" target="body">下载</a></td></tr> </table> </body> </html>
upload.jsp <html> <body > <form action="${pageContext.request.contextPath}/UploadServlet" method="post"enctype="multipart/form-data"> <table align="center" border="1px" width="50%"> <tr><td width="100px">上传者:</td><td><input type="text" name="username"/></td></tr> <tr><td width="100px">选择文件:</td><td><input type="file" name="file"/></td></tr> <tr><td width="100px">资源描述:</td><td><textarea cols="70" rows="5"name="description"></textarea></td></tr> <tr><td align="center" colspan="2"><input type="submit" value="上传"/></td></tr> </table> </form> </body> </html>
好了,自己试试吧!