一般に、サーブレットを使用してフォーム要素を処理する場合、フォーム要素はすべて単純なテキストであり、サーブレットはrequest.getParameter()で簡単に処理できます。しかし、フォームにファイルフィールドのアップロードなど、単純なテキスト以上のものが含まれている場合、httpservletrequestオブジェクトからコンポジットフォームの各サブパートを直接解析することは非常に複雑なタスクです。
「MultiPart/Form-Data」タイプデータの処理を簡素化するために、対応するコンポーネントを処理に使用できます。これは、多くのコーディングを節約し、再利用をサポートし、非常に効率的です。
Javaコンポーネントもいくつかあります:Fileupload、Smartupload、COSなど。この記事では、ApacheのFileuploadで説明します。
Fileuploadを使用するには、最初に対応するコンポーネントをダウンロードする必要があります。
1.Fileuploadパッケージ:http://commons.apache.org/fileupload/
2.IOパッケージ: http://commons.apache.org/io/
ダウンロードした後、zipパッケージを解凍して、Commons-fileupload-1.2.1.jarとcommons-io-1.4.jarをTomcatのWebApp/Web-INF/LIBにコピーしてください。
1。フォームページ(enctype = "multipart/form -data"の指定)-upload.html
<html> <head> <title> upload </title> </head> <body> <form name = "uploadform" method = "post" enctype = "multipart/form-data" action = "upload"> <table> <td> <div align = "right">ユーザー名:</div> </td> <"" </td> </tr> <tr> <td> <div align = "right"> upload file1:</div> </td> <td> <入力タイプ= "file1" size = "30"/> </td> </tr> <tr> <td> <td> <td> <td> <divign = "righ name = "file2" size = "30"/> </td> </tr> <tr> <td> <入力タイプ= "submit" name = "submit" value = "upload"> </td> <td> <inputタイプ= "reset" reset "reset"> </td> </tr </tail
2。サーブレット処理フォーム-UploadServlet
パッケージmypack; import javax.servlet。*; import javax.servlet.http。*; import java.io。*; import java.util。*; import org.apache.commons.fileupload。*; import org.apache.commons.fileupload.servlet org.apache.commons.fileupload.disk。*; public class uploadservletはhttpservlet {private string filepath; //アップロードされたファイルがprivate string tempfilepathであるディレクトリ。 //一時ファイルが保存されているディレクトリpublic void init(servletconfig config)throws servletexception {super.init(config); filepath = config.getInitParameter( "filepath"); tempfilepath = config.getInitParameter( "tempfilepath"); filepath = getServletContext()。getRealPath(filepath); tempfilepath = getServletContext()。getRealPath(tempfilepath); } public void dopost(httpservletrequest request、httpservletresponse応答)throws servletexception、ioexception {respons.setcontenttype( "text/plain"); //クライアントに応答本体を送信しますprintwriter outnet = respons.getWriter(); try {//ハードディスクベースのfileitem Factory DiskFileItemFactory = new DiskFileItemFactory(); //データをハードディスクに書き込むために使用されるバッファのサイズを設定します。ここに4K Factory.SetsizethReshold(4*1024)があります。 //一時ディレクトリFactory.setRepository(新しいファイル(tempfilepath))を設定します。 //ファイルの作成プロセッサservletfileupload upload = new servletfileupload(Factory); //アップロードされるファイルの最大サイズを設定します。ここに4M upload.setsizemax(4*1024*1024)があります。 list / * fileitem * / items = upload.parserequest(request); iterator iter = items.iterator(); while(iter.hasnext()){fileItem item =(fileItem)iter.next(); if(item.isformfield()){processform(item、outnet); //通常のフォームフィールドを処理} else {processuploadedfile(item、outnet); //ファイルをアップロードする}} outnet.close(); } catch(Exception e){新しいservletexception(e); }} private void processformfield(fileitem item、printwriter outnet){string name = item.getFieldName(); string value = item.getString(); outnet.println(name+":"+value+"/r/n"); } private void processuploadedfile(fileitem item、printwriter outnet)スロー例外{string filename = item.getName(); int index = filename.lastindexof( "//"); filename = filename.substring(index+1、filename.length()); long filesize = item.getSize(); if(filename.equals( "")&& filesize == 0)return; file uploadedfile = new file(filepath+"/"+filename); item.write(uploadedfile); outnet.println(filename+"is saved。"); outnet.println( ""+filename+"のサイズは"+filesize+"/r/n"); }}サーブレットは、web.xmlで構成されています。
<Servlet> <Servlet-Name> upload </servlet-name> <servlet-class> mypack.uploadservlet </servlet-class> <init-name> filepath </param-name> <param-value> store </param-value> </init-param> <init-name> <param-name> </param-name> </param-name> <param-value> temp </param-value> </init-param> </servlet> <servlet-name> upload </servlet-name> <url-pattern>/upload </url-pattern> </servlet-mapping>
この時点で、簡単なファイルアップロード機能が完了しました - フォームページにアクセスし、ファイルを選択して、ファイルをアップロードします。ファイルをサーバーにアップロードしながらファイルをデータベースに保存する場合は、ファイル名を取得した後にファイル名をデータベースに保存して、将来ファイル名に従ってユーザーのファイルを選択できるようにします。
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。