何もすることはないので、アップロードとダウンロード機能を実装するためのサーブレットを書きました。サービスを開始した後、LAN内の小さなファイルサーバーになることができます。
1。準備
2つのJARパッケージをダウンロードします。
commons-fileupload-1.3.1.jar
Commons-Io-2.2.jar
2。Webプロジェクトを作成します
私のプロジェクトはZ-uploadと呼ばれています
3.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/nns/javaee xsi:schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/ns/javaee/web-app_0.0.0.xsd" "id" "id" id "id" webaee/wweb-app_0.xsdd <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 </サーブレットマッピング> </web-app>
上記の構成から、私のサーブレットクラスがUploadServiceであり、一致するURLが /*であることがわかります。これは、すべてのアクセスURLと一致することを意味します。
4。サーブレットクラスを書きます
パッケージcom.syz.servlet; Import java.io.file; Import java.io.fileinputStream; Import java.io.fileoutputStream; Import java.io.io.io.ioexception; Import java.io.outputStream; Import Java.io.imprintwriter; Import java.text.simpledate; java.util.date; Import java.util.iterator; Import java.util.list; Import javax.servlet.servletcontext; import javax.servlet.servletexception; Import javax.servlet.servlet.http.httpservlet; 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 uploadservlet 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)servletexception、ioexception {system.out.println( "execute ..."); system.out.println( "------------ begin ------------"); req.setcharacterencoding( "utf-8"); string host = req.getRemoteHost(); System.out.println( "host:" + host);文字列uri = req.getRequesturi(); System.out.println( "uri:" + uri); servletcontext servletcontext = this.getServletConfig().getServletContext(); //ファイル文字列をアップロードするベースパスbasepath = servletcontext.getRealPath(upload_dir); //コンテキストパス文字列contextpath = servletcontext.getContextPath(); System.out.println( "ContextPath:" + ContextPath); //コンテキストのインターセプト後のパス文字列action = uri.substring(contextpath.length()); system.out.println( "action:" + action); //異なる処理は、異なるアクションに従って実行されます。 } 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(リポジトリ); 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> item = items.iterator(); while(ite.hasnext()){fileitem item = item.next(); if(item.isformfield()){// handle formfield} else {//ハンドルファイル文字列fieldname = item.getfieldname();文字列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 + " +" + isinmemory + "/t" + sizeinbytes);ファイル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(); }} //文字列href1 = contextpath +リストを処理した後、ファイルリストにリダイレクトします。 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;ブールフラグ= false; for(int i = 0; i <len; i ++){file f = list [i];文字列fn = f.getName(); if(f.isfile()&& fn.lastindexof( "_")> -1){string fid = fn.substring(fn.lastindexof( "_")); if(id.equals(fid)){download(f、resp); flag = true;壊す; }}} 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;ブールフラグ= false; for(int i = 0; i <len; i ++){file f = list [i];文字列fn = f.getName(); if(f.isfile()&& fn.lastindexof( "_")> -1){string fid = fn.substring(fn.lastindexof( "_")); if(id.equals(fid)){f.delete(); flag = true;壊す; }}} if(flag){//文字列href1 = contextpath + listを処理した後、ファイルリストページにリダイレクトします。 resp.sendredirect(href1); } else {notfound(contextpath、rep); }} else {show404(contextpath、resp); } System.out.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- PrintWriter = rec.getWriter();ファイルリストに戻ります</b> "); out.write(" </body> "); out.write(" </html> "); out.close();} private void form(string contextpath、httpservletresponse resp)スローIoexception {resp.setcontenttype(resp.setcontenttype(" resp.setcontenttype( "text/html; html; charset = sucf-8");文字列href1 = contextpath + list; out.write( "<head> <title> form </title> </head>"); 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 = 'upload'/> <br>"); out.write( "</form>"); out.write( "</body>"); out.write( "</html>"); out.close(); } private void notfound(string contextpath、httpservletresponse rep)throws ioexception {resp.setContentType( "text/html; charset = utf-8"); printwriter out = resp.getWriter();文字列href1 = contextpath + list; out.write( "<html> <body> <b>操作に失敗しました!ファイルが存在しないか、ファイルが削除されていません! out.close(); } private void download(ファイルf、httpservletresponse rep)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)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> </head>"); out.write( "<body>"); out.write( "<b> <a href = '" + href_u + "'> upload </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( "</tr>"); out.write( "<tbody>");ファイル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());文字列fn = f.getName(); if(f.isfile()&& fn.lastindexof( "_")> -1){string filename = fn.substring(0、fn.lastindexof( "_")); string id = fn.substring(fn.lastindexof( "_"));文字列href1 = contextpath + download + "?id =" + id;文字列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 confism(/"削除する?/"); '>削除</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 rep)servletexception、ioexception {system.out.println( "doget ..."); execute(req、rep); } public void dopost(httpservletrequest req、httpservletresponse rep)servletexception、ioexception {system.out.println( "dopost ..."); execute(req、rep); } private string getSuffix(){date date = new date(); simpledateFormat sdf = new SimpledateFormat( "yyyymmdhhmmsssssss"); string suffix = sdf.format(date);接尾辞を返します。 }}実際、UploadServiceクラスは、DoGetおよびDoPostメソッドを実装せずにサービス方法を直接実装できます。
上記のサーブレットについては何も説明したくありません。自分のコードを読んでください。
5。繁殖図
1。プロジェクト構造図
2.404ページ
/*すべてのnull文字と一致するため、写真のパスは一致します。これは、この時点でのアクションがヌル文字であるため、UploadServiceのIF判断に並べられます。
3.ファイルリストページ
4.フォームページをアップロードします
5。ダウンロード
6.削除
7.ファイルは見つかりません。 [削除]をクリックしたときにサーバーにファイルが存在しなくなった場合、このページを入力します。
8。パッケージ化されたソースコードプロジェクトと戦争パッケージ
その中で、Z-uploadはEclipse Sourceコードプロジェクトであり、Z-Upload.WarはReady Warパッケージです
プロジェクト全体には、1つのWeb.xmlと1つのサーブレットクラスの2つのJARパッケージのみがあります。記事からコピーしてテストできます。怠け者なら、ダウンロードできます。
http://download.csdn.net/detail/yunsyz/9569680、特別なリマインダー、1ポイントのダウンロード。
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。