この記事では、Spring Bootを使用してファイルを分散ファイルシステムFASTDFSにアップロードする方法について説明します。
このプロジェクトは、以前のプロジェクトに基づいて構築されます。
1。POMパッケージの構成
Spring Bootの最新バージョン1.5.9を使用して、JDKは1.8、Tomcat8.0を使用します。
<Dependency> groupId> org.csource </groupId> <ArtifActid> fastDFS-Client-Java </artifactid> <バージョン> 1.27-snapshot </version> </dependency>
FastDFS-Client-Javaパッケージを追加して、FastDFS関連のAPIを呼び出しました。
2。構成ファイル
リソースディレクトリにFDFS_CLIENT.CONFファイルを追加します
connect_timeout = 60network_timeout = 60charset = utf-8http.tracker_http_port = 8080http.anti_steal_token = nohttp.secret_key = 123456tracker_server = 192.168.53.85:22222222222Tracker_server = 192.168.53.86:22122
構成ファイルは、接続タイムアウト時間、エンコード形式、tracker_serverアドレス、その他の情報を設定します。
詳細のリファレンス:FASTDFS-CLIENT-JAVA
3。FASTDFSアップロードツールクラスをカプセル化します
FastDfsFileをカプセル化し、基本的なファイル情報にはファイル名、コンテンツ、ファイルタイプ、著者などが含まれます。
パブリッククラスfastdfsfile {private string name;プライベートバイト[]コンテンツ;プライベート文字列ext;プライベートストリングMD5;プライベートストリング著者; // GetterとSetterを省略しますFastDFSClientクラスをカプセル化します。これには、アップロード、ダウンロード、削除などの一般的に使用されるメソッドが含まれます。
まず、クラスがロードされているときに対応する構成情報を読み、初期化します。
static {try {string filepath = new ClassPathResource( "fdfs_client.conf")。getFile()。getAbsolutepath();; clientGlobal.init(filepath); TrackerClient = new TrackerClient(); trackerServer = trackerient.getConnection(); StoragesErver = trackErclient.getStorestorage(TrackerServer); } catch(Exception e){logger.error( "fastdfs client init fail!"、e); }}ファイルアップロード
public static string [] upload(fastdfsfile file){logger.info( "file name:" + file.getName() + "file length:" + file.getContent()。length); namevaluepair [] meta_list = new NameValuePair [1]; Meta_List [0] = new NameValuePair( "author"、file.getauthor()); long starttime = system.currenttimemillis(); string [] uploadResults = null; try {storageclient = new StorageClient(TrackerServer、StoragesErver); uploadResults = storageclient.upload_file(file.getContent()、file.getext()、meta_list); } catch(ioException e){logger.error( "file:" + file.getname()、e)のuploadindの場合のIO例外。 } catch(Exception e){logger.error( "file:" + file.getName()、e)のuploadindの場合の非io例外。 } logger.info( "upload_file使用済み:" +(system.currenttimemillis() - starttime) + "ms"); if(uploadResults == null){logger.Error( "ファイルfail、エラーコード:" + storageclient.getErrorCode()); } string groupName = uploadResults [0];文字列remoteFileName = uploadResults [1]; logger.info( "ファイルを正常にアップロード!!!" + "group_name:" + groupName + "、remoteFileName:" + "" + remoteFileName); uploadResultsを返します;}FASTDFSが提供するクライアントStorageClientを使用してファイルをアップロードし、最後にアップロード結果を返します。
GroupNameとファイル名に基づいてファイル情報を取得します。
public static fileInfo getFile(String GroupName、String RemoteFileName){try {storageClient = new StorageClient(TrackerServer、StoragesErver); return storageclient.get_file_info(groupName、remotefileName); } catch(ioException e){logger.error( "IO例外:高速dfs Failed"からファイルを取得 "、e); } catch(Exception e){logger.error( "non io例外:fast dfs failed"からファイルを取得 "、e); } nullを返します;}ファイルをダウンロードします
public static inputstream downfile(string groupname、string remotefilename){try {storageclient = new storageClient(trackerServer、storageserver); byte [] filebyte = storageclient.download_file(groupName、remotefileName); inputstream ins = new bytearrayinputStream(filebyte); INSを返します。 } catch(ioException e){logger.error( "IO例外:高速dfs Failed"からファイルを取得 "、e); } catch(Exception e){logger.error( "non io例外:fast dfs failed"からファイルを取得 "、e); } nullを返します;}ファイルを削除します
public static void deletefile(String GroupName、String RemoteFileName)スロー例外{storageClient = new StorageClient(TrackerServer、StoragesErver); int i = storageclient.delete_file(groupName、remotefileName); logger.info( "ファイルを正常に削除!!!" + i);}FastDFSを使用する場合は、FASTDFSCLIENTの対応する方法を呼び出してください。
4.コントロールのアップロードクラスを書き込みます
MultiPartFileからファイル情報を読み取り、FastDFSClientを使用してファイルをFASTDFSクラスターにアップロードします。
public string savefile(multipartfile multipartfile)throws ioexception {string [] fileabsolutepath = {}; string filename = multipartfile.getoriginalfilename(); string ext = filename.substring(filename.lastindexof( "。") + 1); byte [] file_buff = null; inputstream inputstream = multipartfile.getInputStream(); if(inputstream!= null){int len1 = inputstream.abailable(); file_buff = new byte [len1]; inputstream.read(file_buff); } inputstream.close(); fastdfsfile file = new fastdfsfile(filename、file_buff、ext); try {fileabsolutepath = fastdfsclient.upload(file); // fastdfsにアップロード} catch(例外e){logger.error( "ファイル例外!"、e); } if(fileabsolutepath == null){logger.error( "ファイルのアップロードが失敗しました、もう一度アップロードしてください!"); } string path = fastdfsclient.getTrackerurl()+fileabsolutepath [0]+"/"+fileabsolutepath [1];戻るパス;}コントロールを要求し、上記のメソッドsavefile()を呼び出します。
@postmapping( "/upload")// 4.3public string singlefileupload(@requestparam( "file")multipartfileファイル以来の新しいアノテーション、Redirectattributes redirectattributes){if(file.isempty()){redirectattributes.addflashattribute( "); "redirect:uploadstatus"を返します。 } try {//ファイルを取得してどこかに保存するstring path = savefile(file); Redirectattributes.addflashattribute( "Message"、 "Your Your Your Your Your custerfully Uploaded '" + file.getoriginalFileName() + "'"); Redirectattributes.addflashattribute( "path"、 "file path url '" + path + "'"); } catch(Exception e){logger.error( "File Failed"、e); } "redirect:/uploadstatus";}を返しますアップロードが成功したら、ページへのファイルパスを表示すると、レンダリングは次のとおりです。
ブラウザのこのURLにアクセスすると、FASTDFSを介して正常に表示されていることがわかります。
これは、Spring Bootを使用してFASTDFSを統合します。
サンプルコード-Github
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。