まず、ファイルのアップロードを紹介します
エンティティクラス
java.sql.timestampをインポートします。 / ** * * @describedファイルアップロードエンティティクラス * */ public class upfile {private string id; // idプライマリキーはプライベート文字列uuidnameをランダムに生成します。 // uuid名プライベート文字列filename; //ファイル名プライベート文字列savepath; //パスプライベートタイムスタンプアップロード時間を保存します。 //プライベート文字列のアップロード://ファイル説明プライベート文字列ユーザー名。 // username public upfile(){super(); } public upfile(string id、string uuidname、string filename、string savepath、timestamp uploadtime、string description、string username){super(); this.id = id; this.uuidname = uuidname; this.fileName = filename; this.savepath = savepath; this.uploadtime = uploadtime; this.description = description; this.username = username; } public string getDescription(){return description; } public string getFileName(){return filename; } public string getId(){return id; } public string getSavePath(){return savepath; } public Timestamp getuploadtime(){return uploadtime; } public string getUsername(){return username; } public string getuuidname(){return uuidname; } public void setDescription(string description){this.description = description; } public void setFileName(string filename){this.filename = filename; } public void setid(string id){this.id = id; } public void setSavePath(String SavePath){this.savePath = SavePath; } public void setuploadtime(Timestamp Uploadtime){this.uploadtime = uploadtime; } public void setUsername(string username){this.username = username; } public void setuuidname(string uuidname){this.uuidname = uuidname; }}ページ
<%@ page Language = "java" import = "java.util。*" pageencoding = "utf-8"%> <%string path = request.getContextPath(); string basepath = request.getscheme()+"://"+request.getServername()+":"+request.getServerport()+path+"/"; %> <!doctype html public " - // w3c // dtd html 4.01 transitional // en"> <html> <head> <base href = "<%= basepath%>"> <title> my jsp 'upload.jsp'スタートページ</title> <meta http-equiv = "pragma" http-equiv = "cache-control" content = "no-cache"> <meta http-equiv = "content =" 0 "> <meta http-equiv =" keyword1、keyword3 "keyword3"> <meta http-equiv = "content =" type = "text/css" href = "styles.css"> - > </head> <body> <body> <h1> file upload </h1> <form action = "$ {pagecontext.request.contextpath}/upload"メソッド= "enctype =" multipart/form-data "> <teable> <tr <tr <tr <tr> <tr> <td> <入力タイプ= "text" name = "username"/> </td> </tr> <tr> <td> upload file:</td> <td> <input type = "file" name = "file"/> </td> </tr> <tr> <td>説明:</td> <td> <textarea rows = "50" 50 "50" 50 " name = "description"> </textarea> </td> </tr> <tr> <td> <入力タイプ= "value =" upload start "/> </td> </tr> </table> </form> <div> $ {msg} </body> </html>サーブレット
java.io.ioexceptionをインポートします。 javax.servlet.servletexceptionをインポートします。 javax.servlet.http.httpservletをインポートします。 javax.servlet.http.httpservletrequestをインポートします。 javax.servlet.http.httpservletResponseをインポートします。 org.apache.commons.fileupload.fileuploadbase.filesizelimitex cehcededexception; Import org.apache.commons.fileupload.fileuploadbase.sizelimitex cehcededexception; Import org.apache.commons.fileupload.servlet.servletfileupload; com.itheima.domain.upfileをインポートします。 com.itheima.exception.myexceptionをインポートします。 com.itheima.service.upfileserviceをインポートします。 com.itheima.service.impl.upfileserviceimplをインポートします。 com.itheima.untils.webuntilをインポートします。 public class uploadfileservletは、httpservlet {public void doget(httpservletrequest request、httpservletresponse応答)servletexception、ioexception {dopost(request、response); } public void dopost(httpservletrequest request、httpservletresponse応答)servletexception、ioexception {//フォームが複数の部品で構成されているかどうかを判断します。 request.getRequestDispatcher( "/upload.jsp")。戻る ; } //マルチパートの場合は、アップロードされたすべての情報を含むファイルアップロードオブジェクトを取得してトラバースしてください{upfile upfile = webuntil.upload(request); upfileservice upfileservice = new upfileserviceimpl(); boolean flag = upfileservice.add(upfile); if(flag){request.setattribute( "msg"、 "upload success"); request.getRequestDispatcher( "/upload.jsp")。戻る ; } else {request.setAttribute( "MSG"、 "アップロード障害、再試行してください"); request.getRequestDispatcher( "/upload.jsp")。戻る ; }} catch(filesizelimitex cheededexception e){e.printstacktrace(); request.setattribute( "msg"、 "シングルファイルサイズ、最大制限を超える"); request.getRequestDispatcher( "/upload.jsp")。戻る ; } catch(sizelimitex cheededexception e){e.printstacktrace(); request.setattribute( "msg"、 "合計ファイルサイズ、最大制限を超えます"); request.getRequestDispatcher( "/upload.jsp")。戻る ; }}}ツール
java.io.fileをインポートします。 java.io.filenotfoundexceptionをインポートします。 java.io.fileoutputStreamをインポートします。 java.io.ioexceptionをインポートします。 java.io.inputStreamをインポートします。 java.io.outputStreamをインポートします。 java.io.usupportedencodingexceptionをインポートします。 java.util.arraylistをインポートします。 java.util.listをインポートします。 java.util.uuidをインポートします。 javax.servlet.http.httpservletrequestをインポートします。 org.apache.commons.fileupload.fileitemをインポートします。 org.apache.commons.fileupload.fileuploadbaseをインポートします。 org.apache.commons.fileupload.fileuploadbase.filesizelimitex cehcededexception; org.apache.commons.fileupload.fileuploadexceptionをインポートします。 org.apache.commons.fileupload.progresslistenerをインポートします。 org.apache.commons.fileupload.disk.diskfileitemfactoryをインポートします。 Import org.apache.commons.fileupload.servlet.servletfileupload; com.itheima.domain.upfileをインポートします。 com.itheima.exception.myexceptionをインポートします。 / ** *ファイルアップロードツールクラス * @describe todo * */ public class webuntil {/ ** * file upload method * @param request pass in request parameter in upfile object * @throws filesizelimitexedexception * @throws sizelimitexededexception * @throws ioexception * filesizelimitex hecededexception、sizelimitex cueededexception {upfile upfile = new upfile(); ArrayList <String> fileList = initList(); try {//ディスクファイルオブジェクトファクトリーDISKFILEITEMFACTORY FACTORY = new DiskFileItemFactory(); string tmp = request.getSession()。getServletContext()。getRealPath( "/tmp"); System.out.println(TMP); // Factory SetFactory(Factory、TMP)を初期化します。 //ファイルアップロードParser ServletFileupload upload = new ServletFileupload(Factory); //パーサーSetupload(upload)を初期化します。 // file list <fileitem> list = upload.parserequest(request); // Travel for(fileItem items:list){//それが通常のフォームオブジェクトであるかどうかを判断しますif(items.isformfield()){//アップロードフォームの名前をstring fieldname = items.getFieldName(); // value string fieldvalue = items.getString( "utf-8"); //裁判官if( "username" .equals(fieldname)){// set upfile.setusername(fieldvalue); } else if( "description" .equals(fieldname)){//属性upfile.setdescription(fieldvalue); }} else {//ファイルはアップロードする準備ができています//ファイル名を取得する文字列filename = items.getName(); //異なるブラウザのために取得されたファイル名の違いを処理しますint index = filename.lastindexof( "//"); if(index!= -1){filename = filename.substring(index+1); } //ランダムファイル名を生成する文字列uuidname = generatefileName(filename); //アップロードされたファイルパス文字列savepath = request.getSession()。getServletContext()。getRealPath( "/web-inf/upload"); //リクエストオブジェクトで入力ストリームを取得しますinputstream in = items.getInputStream(); //ファイルを破壊して別のパスに保存し、パスSavePath = GeneraterAndomDir(SavePath、uuidName)を見つけます。 //ファイルuploadFile(in、savepath、uuidname)をコピーします。 string id = uuid.randomuuid()。toString(); upfile.setid(id); upfile.setsavepath(savepath); upfile.setuidname(uuidname); upfile.setfileName(filename); // calche items.delete();をクリアします。 }}} catch(fileuploadbase.filesizelimitex ceehryedexception e){//例外スローe; } catch(fileuploadbase.sizelimitex cueededexception e){//例外スローe; } catch(fileuploadexception e){e.printstacktrace(); } catch(unsupportedencodingexception e){e.printstacktrace(); } catch(ioexception e){e.printstacktrace(); } catch(Exception e){e.printstacktrace(); } upfileを返します。 } / ***ファイルリストを初期化* @return* / private static arraylist <string> initlist(){arraylist <string> list = new arraylist <string>(); list.add( "。jpg"); list.add( "。rar"); list.add( "。txt"); list.add( "。png");返品リスト。 } /***ファイルのコピー* @paramの入力ストリームアイテム* @param savepath save path* /prival uuidname file name* /private static void uploadfile(inputstream in、string savepath、string uuidname){// get file file = newファイル(save、uuidname); outputStream out = null; try {int len = 0; byte [] buf = new byte [1024]; //出力ストリームを取得= new fileoutputStream(file); while((len = in.read(buf))!= -1){out.write(buf、0、len); }} catch(filenotfoundexception e){e.printstacktrace(); } catch(ioexception e){e.printstacktrace(); }最後に{try {in.close(); } catch(ioexception e){e.printstacktrace(); } try {out.close(); } catch(ioexception e){e.printstacktrace(); }}} /***ランダムストレージパスを生成* @param SavePath Save Path* @param uuid name* @return*ハッシュコードを使用して完成* /private static string generaterandomdir(string savepath、string uuidname){// hashcode system.out.out.outln(save path "+save path" system.out.println( "uuidname"+uuidname); int hashcode = uuidname.hashcode(); // container stringbuilder sb = new StringBuilder(); while(hashcode> 0){// int 15 int tmp = hashcode&0xf; sb.append( "/"); sb.append(tmp+""); HashCode = HashCode >> 4; } //新しいパス文字列パス= savepath+sb.toString(); system.out.println( "path"+path); file file = new file(path); //パスが存在するかどうかを判断します(!file.exists()){// file.mkdirs(); } // Save Path Return Pathを返します。 } / ***新しいファイル名を生成* @param uuidnameランダムid名* @param filename original name* @return* / private static string generatefilename(string filename){string uuidname = uuid.randomuid()。toString(); return uuidname.replace( " - "、 "").toString()+"_"+filename; } / ***初期化パーサー* @param upload* / private static void setupload(servletfileupload upload){// upload.setheaderencoding( "utf-8"); //ファイルサイズupload.setFilesizemax(1024*1024*20); //合計ファイルサイズupload.setsizemax(1024*1024*50)を設定します。 // Progressリスナーupload.setProgressListener(new ProgressListener(){public void update(long pbytesread、long pcontentlength、int pitems){system.out.pitln( "read:"+pbytesread+"、total:"+pcontentlength+"、"+pitems+"); piter Factory*/ private void setFactory(diskfileitemactory Factory){///初期化バッファーFactory.SetsizeThreshold(1024*1024) 2つのファイルをダウンロードします
サーブレット
public class downUpfileservletは、httpservlet {public void doget(httpservletrequest request、httpservletresponse応答)servletexception、ioexception {dopost(request、response); } public void dopost(httpservletrequest request、httpservletResponse応答)servletexception、ioexception {// get id string id = request.getparameter( "id"); //ビジネスレイヤーのインターフェイスupfileservice upfileservice = new upfileserviceimpl(); // ID upfile upfile = upfileservice.findupfilebyid(id)に基づいてこのオブジェクトを見つけます; if(upfile == null){return; } //ファイル文字列filename = upfile.getFileName()の本名を取得します。 //ファイル名に中国語がある場合、それはトランスコードされる必要があります。そうしないと、ファイル名Filename = urlencoder.encode(filename、 "utf-8"); //名前を変更しましたstring uuidname = upfile.getuuidname(); //パス文字列savepath = upfile.getSavePath();ファイルfile = new File(SavePath、uuidname); //ファイルが存在するかどうかを決定します(!file.exists()){request.setattribute( "msg"、 "ダウンロードされたファイルが期限切れになっています"); request.getRequestDispatcher( "/index")。戻る; } //ファイルを設定します。応答ヘッダー情報応答をダウンロードします。 // IOストリームを使用してinputstream in = new fileinputStream(file); servletoutputStream out = respons.getOutputStream(); int len = 0; byte [] buf = new byte [1024]; while((len = in.read(buf))!= -1){out.write(buf、0、len); } in.close(); }}データベース
データベースupload_download_exercise; upload_download_exerciseを使用してください。テーブルアップファイルを作成します(ID varchar(100)、// UUIDを使用してUUIDNAME VARCHAR(255)、// UUID PLUS ORIGINAL FILE NAME FILENAME VARCHAR(100)、//実際のファイル名SavePath Varchar(255)、// Save Uploadtimeタイムスタンプ、//アップロード時間説明Varchar(255)、//
上記は、commos-fileuploadを使用してファイルのアップロードとダウンロードを実現するJavaの関連コンテンツです。すべての人に役立つことを願っています。