Java Web画像のアップロードとファイルアップロード
画像のアップロードとファイルアップロードは本質的に同じであり、画像自体もファイルです。ファイルアップロードは、画像をサーバーにアップロードすることです。多くの方法はありますが、基礎となる実装はすべてファイルの読み取りと書き込みに関するものです。
注意すべきこと
1.フォームは属性enctype = "multipart/form-data"を記述する必要があります
2。ファイルを正常にアップロードできるようにするために、ファイルコントロールの名前属性値は、送信した制御層変数名と一致する必要があります。
たとえば、スペース名がファイルの場合、バックグラウンドで定義する必要があります
プライベートファイルファイル。 //ファイル制御名
private string filecontenttype; //画像タイプ
プライベート文字列filefileName; //ファイル名
1.JSPページ
<%@ page Language = "Java" contentType = "text/html; charset = utf-8" pageencoding = "utf-8"%> <! <html> <head> <メタhttp-equiv = "content-type" content = "text/html; charset = utf-8"> <meta http-equiv = "pragma" content = "no-cache"/> <base target = "_ self"> <title> file upload </head> <body> <body> <> <> <> <> <> <> < enctype = "multipart/form-data"> <input type = "file" name = "file" value "> <input type =" submit "value ="識別 "> </form> </body> </html>
1。ページデータに送信する必要があるコントローラー
パッケージcom.cpsec.tang.chemical.action; import java.io.file; import java.io.ioexception; import java.util.random; import javax.annotation.resource; import javax.servlet.servlet.http.httpservletrequest; import org.commons.commons.filetils; org.apache.struts2.servletactioncontext; Import org.springframework.stereotype.controller; Import com.cpsec.tang.chemical.chemical.biz.lunbobiz; import com.cpsec.tang.chemical.entity.image; inmoper.opensymphony.xword.xwork2. conpport; LunboactionはActionSupportを拡張します{ / ** * * / private static final long serialversionuid = 1l; @resource(name = "lunbobiz")private lunbobiz lunbobiz;プライベート画像画像;プライベートファイルファイル。 //ファイルコントロール名プライベート文字列filecontentType; //画像タイププライベート文字列filefileName; //ファイル名プライベート整数番号。 public string indimage(){image = lunbobiz.findimage();成功を返す; } public string alterimage(){image = lunbobiz.findimage();成功を返す; } public string alterimage1(){httpservletrequest request = servletactionContext.getRequest(); string root = request.getRealPath( "/upload"); //画像がアップロードされるサーバーパスstring names [] = filefilename.split( "//。");文字列filename = ""; if(names.length> = 1){filename = getRandomString(20)+"。"+names [names.length-1]; } string picpath = "upload/"+filename; //データベースファイルに保存された画像のパスfile1 = new file(root); try {fileutils.copyfile(file、new file(file1、filename)); }} catch(ioexception e){e.printstacktrace(); }成功を返す; } /*ランダムな文字列を取得* /public string getRandomString(int length){//生成された文字列の長さを示しますstring base = "abcdefghijklmnopqrstuvwxyz0123456789"; RANDOM RANDOM = new Random(); stringbuffer sb = new StringBuffer(); for(int i = 0; i <length; i ++){int number = random.nextint(base.length()); sb.append(base.charat(number)); } return sb.toString(); }}これはコピーしてファイルをアップロードすることであり、他の方法があります
方法2
@Controller( "ContractAction")Public Class ContractActionはActionSupportを拡張します{プライベート最終静的文字列uploaddir = "/files"; //ファイルをアップロードするパス、WebContentの下でプライベートファイルを作成します。 //入力制御名はファイルである必要があります// filenameコレクションプライベート文字列filefileNameをアップロードします。 //ファイルコンテンツのアップロードタイプコレクションプライベート文字列filecontenttype;プライベート文字列ファイル名; public string upload()throws filenotfoundexception、ioexception {string path = uploadfile(); //ファイルへのパス保存データベースの成功。 } // upload関数を実行@suppresswarnings( "deprecation")public string uploadfile()throws filenotfoundexception、ioexception {try {inputstream in = new fileinputStream(file); string dir = servletactionContext.getRequest()。getRealPath(uploadDir);ファイルfilelocation = new file(dir); //アプリケーションルートディレクトリにターゲットアップロードディレクトリを手動で作成することもできます。 (!isCreated){//作成されたターゲットアップロードディレクトリの作成に失敗した場合、カスタム例外をスローするなど、その他の処理を実行できます。この状況は通常発生しません。 nullを返します。 }} // this.setFilefileName(getRandomString(20)); string [] name = this.getFilefileName()。split( "//。"); string filename = getRandomString(20)+"。"+name [name.length-1]; this.setFileFileName(filename); System.out.println(filename);ファイルuploadFile = new File(dir、filename); outputStream out = new FileOutputStream(uploadFile); byte [] buffer = new byte [1024 * 1024]; int length; while((length = in.read(buffer))> 0){out.write(buffer、0、length); } in.close(); out.close(); uploaddir.substring(1)+"//"+filefileNameを返します。 } catch(filenotfoundexception ex){return null; } catch(ioException ex){return null; }} public static string getRandomString(int length){string str = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789"; RANDOM RANDOM = new Random(); stringbuffer sb = new StringBuffer(); for(int i = 0; i <length; i ++){int number = random.nextint(62); sb.append(str.charat(number)); } return sb.toString(); }}単一の画像アップロードに加えて、複数の画像アップロードがあり、原則は同じです
パッケージcom.cpsec.tang.chemical.action; import java.io.file; java.io.fileinputStreamをインポートします。 java.io.filenotfoundexceptionをインポートします。 java.io.fileoutputStreamをインポートします。 java.io.ioexceptionをインポートします。 java.io.inputStreamをインポートします。 java.io.outputStreamをインポートします。 java.util.list; Import javax.servlet.http.httpservletrequest; Import org.apache.struts2.servletactionContext; import com.pensymphony.xwork2.actionsupport; = "/upload"; //ファイルコレクションプライベートリスト<ファイル>ファイルをアップロードします。 //ファイル名のコレクションプライベートリスト<String> fileFileNameをアップロードします。 //ファイルコンテンツのアップロードタイプコレクションプライベートリスト<String> fileContentType; public List <file> getFile(){return file; } public void setFile(list <file> file){this.file = file; } public List <String> getFileFileName(){return filefileName; } public void setFileFileName(List <String> fileFileName){this.filefileName = fileFileName; } public List <String> getFileContentType(){return fileContentType; } public void setFileContentType(List <String> fileContentType){thil.fileContentType = fileContentType; } public string uploadform()スロー例外{httpservletrequest request = servletactioncontext.getRequest(); string webpath = null; // for(int i = 0; i <file.size(); i ++){//各ファイルuploadfile(i); loop upload upload(i); webpath = "upload/"+this.getFilefileName()。get(i); }「成功」を返します。 } //アップロード関数の実行プライベート文字列uploadFile(int i)throws filenotfoundexception、ioexception {try {inputstream in = new fileinputStream(file.get(i)); string dir = servletactionContext.getRequest()。getRealPath(uploadDir);ファイルfilelocation = new file(dir); //ここでは、アプリケーションルートディレクトリにターゲットアップロードディレクトリを手動で作成することもできます。 (!isCreated){//ターゲットアップロードディレクトリが作成されている場合、カスタム例外をスローするなど、他の処理を実行できます。この状況は発生しません。 nullを返します。 }} string filename = this.getFileFileName()。get(i);ファイルuploadFile = new File(dir、filename); outputStream out = new FileOutputStream(uploadFile); byte [] buffer = new byte [1024 * 1024]; int length; while((length = in.read(buffer))> 0){out.write(buffer、0、length); } in.close(); out.close(); uploadfile.toString()を返します。 } catch(filenotfoundexception ex){return null; } catch(ioException ex){return null; }}}読んでくれてありがとう、私はそれがあなたを助けることができることを願っています。このサイトへのご支援ありがとうございます!