java基于servlet编写上传下载功能 类似文件服务器
本人闲来无事,写了个servlet,实现上传下载功能。启动服务后,可以在一个局域网内当一个小小的文件服务器。
一、准备工作
下载两个jar包:
commons-fileupload-1.3.1.jar
commons-io-2.2.jar
二、创建一个web工程
我的工程名叫:z-upload
三、配置web.xml
<?xml version="1.0" encoding="utf-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="webapp_id" version="3.0"> <display-name>z-upload</display-name> <servlet> <servlet-name>uploadservice</servlet-name> <servlet-class>com.syz.servlet.uploadservice</servlet-class> </servlet> <servlet-mapping> <servlet-name>uploadservice</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app>
从以上配置可以看出,我的servlet类是uploadservice,匹配的url是/*,意思是匹配所有访问url。
四、写servlet类
package com.syz.servlet; import java.io.file; 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.text.simpledateformat; import java.util.date; import java.util.iterator; import java.util.list; import javax.servlet.servletcontext; 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.progresslistener; import org.apache.commons.fileupload.disk.diskfileitemfactory; import org.apache.commons.fileupload.servlet.servletfileupload; public class uploadservice extends httpservlet { public static final string list = "/list"; public static final string form = "/form"; public static final string handle = "/handle"; public static final string download = "/download"; public static final string delete = "/delete"; public static final string upload_dir = "/upload"; private static final long serialversionuid = 2170797039752860765l; public void execute(httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception { system.out.println("execute..."); system.out.println("------------begin---------------"); req.setcharacterencoding("utf-8"); string host = req.getremotehost(); system.out.println("host:" + host); string uri = req.getrequesturi(); system.out.println("uri:" + uri); servletcontext servletcontext = this.getservletconfig() .getservletcontext(); // 上传文件的基本路径 string basepath = servletcontext.getrealpath(upload_dir); // 上下文路径 string contextpath = servletcontext.getcontextpath(); system.out.println("contextpath:" + contextpath); // 截取上下文之后的路径 string action = uri.substring(contextpath.length()); system.out.println("action:" + action); // 依据action不同进行不同的处理 if (action.equals(form)) { form(contextpath, resp); } else if (action.equals(handle)) { boolean ismultipart = servletfileupload.ismultipartcontent(req); system.out.println("ismultipart:" + ismultipart); if (!ismultipart) { return; } diskfileitemfactory factory = new diskfileitemfactory(); file repository = (file) servletcontext .getattribute(servletcontext.tempdir); system.out.println("repository:" + repository.getabsolutepath()); system.out.println("basepath:" + basepath); factory.setsizethreshold(1024 * 100); factory.setrepository(repository); servletfileupload upload = new servletfileupload(factory); // 创建监听 progresslistener progresslistener = new progresslistener() { public void update(long pbytesread, long pcontentlength, int pitems) { system.out.println("当前文件大小:" + pcontentlength + "\t已经处理:" + pbytesread); } }; upload.setprogresslistener(progresslistener); list<fileitem> items = null; try { items = upload.parserequest(req); system.out.println("items size:" + items.size()); iterator<fileitem> ite = items.iterator(); while(ite.hasnext()){ fileitem item = ite.next(); if(item.isformfield()){ // handle formfield }else{ // handle file string fieldname = item.getfieldname(); string filename = item.getname(); filename = filename.substring( filename.lastindexof(file.separator) + 1); string contenttype = item.getcontenttype(); boolean isinmemory = item.isinmemory(); long sizeinbytes = item.getsize(); system.out.println(fieldname + "\t" + filename + "\t" + contenttype + "\t" + isinmemory + "\t" + sizeinbytes); file file = new file( basepath + "/" + filename + "_" + getsuffix()); // item.write(file); inputstream in = item.getinputstream(); outputstream out = new fileoutputstream(file); byte[] b = new byte[1024]; int n = 0; while ((n = in.read(b)) != -1) { out.write(b, 0, n); } out.flush(); in.close(); out.close(); } } // 处理完后重定向到文件列表页面 string href1 = contextpath + list; resp.sendredirect(href1); } catch (fileuploadexception e) { e.printstacktrace(); } catch (exception e) { e.printstacktrace(); } } else if (action.equals(list)) { list(contextpath, basepath, resp); } else if (action.equals(download)) { string id = req.getparameter("id"); system.out.println("id:" + id); if (id == null) { return; } file file = new file(basepath); file[] list = file.listfiles(); int len = list.length; boolean flag = false; for (int i = 0; i < len; i++) { file f = list[i]; string fn = f.getname(); if (f.isfile() && fn.lastindexof("_") > -1) { string fid = fn.substring(fn.lastindexof("_")); if (id.equals(fid)) { download(f, resp); flag = true; break; } } } if (!flag) { notfound(contextpath, resp); } } else if (action.equals(delete)) { string id = req.getparameter("id"); system.out.println("id:" + id); if (id == null) { return; } file file = new file(basepath); file[] list = file.listfiles(); int len = list.length; boolean flag = false; for (int i = 0; i < len; i++) { file f = list[i]; string fn = f.getname(); if (f.isfile() && fn.lastindexof("_") > -1) { string fid = fn.substring(fn.lastindexof("_")); if (id.equals(fid)) { f.delete(); flag = true; break; } } } if (flag) { // 处理完后重定向到文件列表页面 string href1 = contextpath + list; resp.sendredirect(href1); } else { notfound(contextpath, resp); } } else { show404(contextpath, resp); } system.out.println("------------end---------------"); } private void show404(string contextpath, httpservletresponse resp) throws ioexception { resp.setcontenttype("text/html;charset=utf-8"); printwriter out = resp.getwriter(); string href1 = contextpath + list; out.write("<html>"); out.write("<head><title>404</title></thead>"); out.write("<body>"); out.write("<b>您所访问的页面不存在!<a href='" + href1 + "'>点击</a>返回文件列表</b>"); out.write("</body>"); out.write("</html>"); out.close(); } private void form(string contextpath, httpservletresponse resp) throws ioexception { resp.setcontenttype("text/html;charset=utf-8"); printwriter out = resp.getwriter(); string href1 = contextpath + list; out.write("<html>"); out.write("<head><title>form</title></thead>"); out.write("<body>"); out.write("<b><a href='" + href1 + "'>点击</a>返回文件列表</b>"); out.write( "<form action='handle' method='post' enctype='multipart/form-data' style='margin-top:20px;'>"); out.write("<input name='file' type='file'/><br>"); out.write("<input type='submit' value='上传'/><br>"); out.write("</form>"); out.write("</body>"); out.write("</html>"); out.close(); } private void notfound(string contextpath, httpservletresponse resp) throws ioexception { resp.setcontenttype("text/html;charset=utf-8"); printwriter out = resp.getwriter(); string href1 = contextpath + list; out.write("<html><body><b>操作失败!文件不存在或文件已经被删除!<a href='" + href1 + "'>点击</a>返回文件列表</b></body></html>"); out.close(); } private void download(file f, httpservletresponse resp) throws ioexception { string fn = f.getname(); string filename = fn.substring(0, fn.lastindexof("_")); system.out.println("filename:" + filename); resp.reset(); resp.setcontenttype("application/octet-stream"); string encodingfilename = new string(filename.getbytes("gbk"), "iso8859-1"); system.out.println("encodingfilename:" + encodingfilename); resp.setheader("content-disposition", "attachment;filename=" + encodingfilename); inputstream in = new fileinputstream(f); outputstream out = resp.getoutputstream(); byte[] b = new byte[1024]; int n = 0; while ((n = in.read(b)) != -1) { out.write(b, 0, n); } out.flush(); in.close(); out.close(); } private void list(string contextpath, string basepath, httpservletresponse resp) throws ioexception { string href_u = contextpath + form; resp.setcontenttype("text/html;charset=utf-8"); printwriter out = resp.getwriter(); out.write("<html>"); out.write("<head><title>list</title></thead>"); out.write("<body>"); out.write("<b>我要<a href='" + href_u + "'>上传</a></b><br>"); out.write( "<table border='1' style='border-collapse:collapse;width:100%;margin-top:20px;'>"); out.write("<thead>"); out.write("<tr>"); out.write("<th>序号</th><th>文件名</th><th>操作</th>"); out.write("</tr>"); out.write("</thead>"); out.write("<tbody>"); file file = new file(basepath); file[] list = file.listfiles(); system.out .println("basepath:" + basepath + "\tlist.size:" + list.length); int len = list.length; int no = 1; for (int i = 0; i < len; i++) { file f = list[i]; system.out.println(i + "\t" + f.getname()); string fn = f.getname(); if (f.isfile() && fn.lastindexof("_") > -1) { string filename = fn.substring(0, fn.lastindexof("_")); string id = fn.substring(fn.lastindexof("_")); string href1 = contextpath + download + "?id=" + id; string href2 = contextpath + delete + "?id=" + id; stringbuilder sb = new stringbuilder(); sb.append("<tr>"); sb.append("<td>"); sb.append(no++); sb.append("</td>"); sb.append("<td>"); sb.append(filename); sb.append("</td>"); sb.append("<td>"); sb.append("<a href='"); sb.append(href1); sb.append("'>下载</a> <a href='"); sb.append(href2); sb.append("' onclick='return confirm(\"您确定要删除吗?\");'>删除</a>"); sb.append("</td>"); sb.append("</tr>"); out.write(sb.tostring()); } } out.write("</tbody>"); out.write("</table>"); out.write("</body>"); out.write("</html>"); out.close(); } public void doget(httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception { system.out.println("doget..."); execute(req, resp); } public void dopost(httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception { system.out.println("dopost..."); execute(req, resp); } private string getsuffix() { date date = new date(); simpledateformat sdf = new simpledateformat("yyyymmddhhmmsssss"); string suffix = sdf.format(date); return suffix; } }
其实uploadservice类可以直接实现service方法,而不用实现doget、dopost方法。
以上servlet我也不想多解释什么,自己看代码吧。
五、效果图
1.项目结构图
2.404页面
/*会匹配所有包括空字符,所以图片中的路径会匹配,在uploadservice中的if判断中出现在else中,因为此时的action是空字符。
3.文件列表页面
4.上传表单页面
5.下载
6.删除
7.文件找不到,如果你点删除时,文件在服务器上已经不存在,那么会进入此页面
8.打包的源码工程和war包
其中z-upload是eclipse源码工程,z-upload.war是打好的war包
全工程就两个jar包,一个web.xml和一个servlet类,可以自己从文章中拷贝过去测试一下,如果是懒人,可以下载
http://download.csdn.net/detail/yunsyz/9569680,特别提醒,下载要1分哦。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: Java的JSON处理器fastjson使用方法详解
下一篇: java list去重操作实现方式