この記事の例は、ファイルのアップロードを共有し、参照用のJava実装コードをダウンロードします。特定のコンテンツは次のとおりです
フロントデスク:
1。提出方法:投稿
2。フォームにファイルアップロードされたフォームアイテムがあります: <入力型= "ファイル" />
3.フォームタイプを指定します。
デフォルトタイプ:enctype = "Application/x-www-form-urlencoded"
ファイルアップロードタイプ:MultiPart/Form-Data
fileupload
ファイルアップロード機能の開発に一般的に使用され、Apacheはファイルアップロードコンポーネントも提供します!
fileuploadコンポーネント:
1.ソースコードをダウンロードします
2.プロジェクトにJARファイルを紹介します
commons-fileupload-1.2.1.jar [ファイルアップロードコンポーネントコアJARパッケージ]
commons-io-1.4.jar [ファイル処理のための刺繍関連ツールクラス]
使用:
public class uploadServlet拡張httpservlet {//アップロードディレクトリ、アップロードされたリソースパブリックボイド(httpservletrequest request、httpservletresponse応答)を保存します。 Factory = new DiskFileItemFactory(); //2。ファイルアップロードコアツールクラスservletfileupload upload = new servletfileupload(Factory); // 1。単一のファイルに許容される最大サイズを設定:30m upload.setFilesizeMax(30*1024*1024); // 2。ファイルアップロードフォームに許容される合計サイズを設定:80m upload.setsizemax(80*1024*1024); //3。アップロードフォームファイル名のエンコードを設定します//等価以下に相当します。setcharacterencoding( "utf-8"); upload.setheaderencoding( "utf-8"); //3。現在のフォームがファイルアップロードフォームであるかどうかif(upload.ismultipartContent(request)){//4。要求されたデータをFileItemオブジェクトに変換し、リスト<fileitem> list = upload.erequest(request); // Traversal:(fileitem item:list){//判断:通常のテキストデータの各アップロードデータを取得しますif(item.isformfield()){//通常のテキストデータ文字列fieldname = item.getfieldname(); //フォーム要素名文字列content = item.getString(); //フォーム要素名、対応するデータ//item.getString(utf-8 ");エンコーディングSystem.out.println(fieldName + "" + content)を指定します。 } //アップロードファイル(ファイルストリーム)---> upload upload Directory else {//通常のテキストデータ文字列fieldname = item.getFieldName(); //フォーム要素名文字列name = item.getName(); //ファイル名文字列content = item.getString(); //フォーム要素名、対応するデータ文字列型= item.getContentType(); //ファイルタイプinputstream in = item.getInputStream(); //ファイルストリームのアップロード/**4。ファイル名は名前が変更されます*さまざまなユーザーreadme.txtファイルの場合、上書きしたくありません! *バックグラウンド処理:ユーザーに一意のタグを追加してください! */ // a。一意のタグ文字列id = uuid.randomuuid()。toString()をランダムに生成します。 // b。ファイルname = id + "#" + nameを備えたスプライス名; // get base base path string path = getservletcontext()。getRealPath( "/upload"); //ターゲットファイルファイル= new File(path、name)を作成します。 //ツールクラス、ファイルアップロードitem.write(file); item.delete(); // System System.out.println()によって生成された一時ファイルを削除します。 }}} else {system.out.println( "現在のフォームはファイルアップロードフォームではなく、処理が失敗!"); }} catch(例外e){e.printstacktrace(); }} //プロセスの手動実装プライベートボイドアップロード(httpservletrequest request)ioException、unsupportedencodingexception { /* request.getParameter( ""); // get/post request.getQueryString(); // get request.getInputStream()によって送信されたデータを取得します。 // postで送信されたデータを取得*//******************手動でファイルアップロードフォームデータ************* // 1。フォームデータストリームinputstream in = request.getInputStream()を取得します。 // 2。 Stream inputStreamReader instream = new inputStreamReader(in、 "utf-8"); // 3。 BufferedReader Reader = new BufferedReader(instream); //出力データ文字列str = null; while((str = reader.readline())!= null){system.out.println(str); } //出力データ文字列str = null; while((str = reader.readline())!= null){system.out.println(str); } // close reader.close(); instream.close(); in.close(); } public void dopost(httpservletrequest request、httpservletresponse応答)servletexception、ioexception {this.doget(request、response); }}場合:
index.jsp
<body> <a href = "$ {pagecontext.request.contextpath}/upload.jsp"> file upload </a> <a href = "$ {pagecontext.request.contextpath}upload.jsp
<body> <form name = "frm_test" action = "$ {pagecontext.request.contextpath}/fileservlet?methed" methed "ost" enctype = "multipart/form-data"> < <入力型= "file" name = "file_img"> <br/> <input type = "submit" value = "submit"> </form> </body>fileservlet.java
/** *ハンドルファイルのアップロードとダウンロード * @Author jie.yuan * * */public class fileservlet extends httpservlet {public void doget(httpservletrequest request、httpservletresponse応答)Servletexception、ioexception、ioexception、ioexception {// requestisuisuisuisuisuisuisuisuisuisuisuisuisuisuisuisuisuisusisuisusisuisusisusisusisusisupedsection {// if( "upload" .equals(method)){// upload upload(request、response); } else if( "downlist" .equals(method)){//ダウンロードリストダウンリスト(リクエスト、応答); } else if( "down" .equals(method)){//ダウンロードダウン(リクエスト、応答); }} / ** * 1。アップロード * / private void upload(httpservletrequest request、httpservletresponse応答)Servletexception、ioexception {try {//1。factoryobject fileitemfactory factory = new diskfileItemfactory(); // 2。ファイルアップロードコアツールクラスServletFileupload upload = new ServletFileupload(Factory); //サイズ制限パラメータupload.setFilesizemax(10*1024*1024); //単一のファイルサイズ制限upload.setsizemax(50*1024*1024); //合計ファイルサイズ制限upload.setheaderencoding( "utf-8"); //中国のファイルエンコードの処理//裁判官if(upload.ismultipartContent(request)){// 3。リクエストデータをリストコレクションリストに変換<fileitem> list = upload.parserequest(request); // Traversal for(fileItem item:list){//判断:通常のテキストデータif(item.isformfield()){// name string name = item.getfieldname(); // value string value = item.getString()を取得します。 System.out.println(value); } //ファイルフォームアイテムelse { / ************ファイルアップロード**************** //ファイル名を取得する文字列name = item.getName(); // ---ファイル名のアップロードの問題を処理します。一意のマーク文字列id = uuid.randomuuid()。toString()を取得します。 // a2。スプライスファイル名name = id + "#" + name; // b。 get upload Directory string basepath = getServletContext()。getRealPath( "/upload"); // c。アップロードされるファイルオブジェクトを作成ファイル= newファイル(basepath、name); // d。 aplody item.write(file); item.delete(); //コンポーネントが実行されているときに生成された一時ファイルを削除}}}}}} catch(Exception e){e.printstacktrace(); }} / *** 2。ダウンロードリストを入力します* / private void nownlist(httpservletrequest request、httpservletresponse応答)スローServletexception、ioException {//実装アイデア:最初にアップロードディレクトリ内のすべてのファイルのファイル名を取得し、次に保存します。 down.jspリストにジャンプして、// 1を表示します。マップコレクションの初期化マップ<ファイル名一意タグ、ショートファイル名>; map <string、string> filenames = new hashmap <string、string>(); // 2。 string bathpath = getServletContext()。getRealPath( "/upload")の下にあるすべてのファイルのアップロードディレクトリとファイル名を取得します。 //ディレクトリファイル= new File(Bathpath); //ディレクトリでは、すべてのファイル名文字列リスト[] = file.list(); // traversal、cenculate if(list!= null && list.length> 0){for(int i = 0; i <list.length; i ++){// full name string filename = list [i]; //短い名前文字列shortname = filename.substring(filename.lastindexof( "#")+1); // filenames.put(filename、shortname)をカプセル化する; }} // 3。domain request.setattribute( "filenames"、filenames)を要求するために保存します。 //4。worwardrequest.getRequestDispatcher( "/downlist.jsp")。 } / *** 3。ダウンロードを処理* / private void down(httpservletrequest request、httpservletresponse応答)Servletexception、ioexception {//ユーザーによってダウンロードされたファイル名を取得します(URLアドレスの後にデータを追加)string filename = request.getParameter( "filename"); filename = new String(filename.getBytes( "ISO8859-1")、 "UTF-8"); //アップロードディレクトリパス文字列basepath = getServletContext()。getRealPath( "/upload"); //ファイルストリームを取得inputstream in = new fileinputStream(new File(basepath、filename)); //ファイル名が中国語の場合、URLエンコードを実行する必要がありますfilename = urlencoder.encode(filename、 "utf-8"); // respons.setheaderをダウンロードするために応答ヘッダーを設定します( "content-disposition"、 "attachment; filename =" + filename); //応答バイトストリームoutputStream out = response.getOutputStream(); byte [] b = new byte [1024]; int len = -1; while((len = in.read(b))!= -1){out.write(b、0、len); } // close out.close(); in.close(); } public void dopost(httpservletrequest request、httpservletresponse応答)servletexception、ioexception {this.doget(request、response); }}上記はこの記事に関するものです。すべての人の学習に役立つことを願っています。