ファイルのアップロードおよびダウンロード関数は、最近のプロジェクトで使用されています。この機能はより重要だと思うので、特別に抽出して自分で試しました。
以下は、参照用のSpringMVC構成環境でファイルをアップロードおよびダウンロードするための特定の手順です。特定のコンテンツは次のとおりです
1。基本構成:
Mavenインポートパッケージと構成pom.xml。 SpringMVCの基本的な依存関係に加えて、ファイルをアップロードするときに使用されるCommons-Io.jsrおよびcommons-fileupload.jarをインポートする必要があります。
<Project XMLNS = "http://maven.apache.org/pom/4.0.0" xmlns:xsi = "http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation = "http://maven.apach/4.0. http://maven.apache.org/maven-v4_0_0.xsd "> <modelversion> 4.0.0 </modelversion> <groupid> filloadtest </groupid> <artifactid> filloadtest </artifactid> <パッケージ> war </packagot> 0.0.1-snapshot <> <> <> <> <> fill-snapshot webApp </name> <url> http://maven.apache.org </url> <burtion> finalName> filloadtest </finalName> <Plugins> <Plugins> <! - 次の構成により、JREバージョンが変更されないようにします。これを設定しない場合、JREは強制更新が強制されるたびに1.5に戻ります - > <Plugin> <Artifactid> maven-compiler-plugin </artifactid> <バージョン> 2.3.2 </version> <source> 1.7 </source> <ターゲット> 1.7 </ターゲット> </ecoding> <bootclasspath> $ {java.home} /lib/rt.jar </bootclasspath> </compilerarguments> </configuration> </plugin> </build> <dependencies> <shepence> <depthency> </dependency> <dependency> groupid> org.springframework </groupid> <artifactid> spring-webmvc </artifactid> <バージョン> 4.0.6. release </version> </dependency> <dependency> com.fasterxml.jackson.core </groupid> <artifactid> <artifactid> <バージョン> 2.2.3 </version> </dependency> <dependency> sgroupid> com.fasterxml.jackson.core </groupid> <artifactid> jackson-core </artifactid> <バージョン> 2.2.3 </version <artifactid> jackson-databind </artifactid> <version> 2.2.3 </version> </dependency> <seplagence> <groupid> commons-fileupload> commons-fileupload </artifactid> <バージョン> 1.3.1 </バージョン> <artifactid> commons-io </artifactid> <バージョン> 2.4 </version> </dependency> </dependencies> </project>web.xmlの基本的な構成:
<?xml version = "1.0" encoding = "utf-8"?> <web-app xmlns:xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns = "http://java.sun.com/xml/nns/javaee xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "id =" webapp_id "バージョン=" 2.5 "> <filter> <説明> charsetフィルター</description> <filter-name> encodingfilter </filter-name> <filter-class> org.springframework.web.filter.characterencodingfilter </filter-class> <init-param> <description> charset encoding </description> <param-name> ending </param-name> <param-value> utf-8 </param-value> </initparam> </<フィルターマッピング> <filter-name> encodingfilter </filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name> springmvc </servlet-name> <servlet-class> org.springframework.web.servlet.dispatchererserer <param-name> contextconfiglocation </param-name> <param-value> classpath:spring.xml </param-value> </init-param> </servlet> <servlet-name> springmvc </servlet-name> <url-pattern>* <welcome-file> index.html </welcome-file> <welcome-file> index.htm </welcome-file> <welcome-file> index.jsp </welcome-file> index.jsp </welcome-file> default.html </welcome-file> <welcome-file> <welcome-file> defoltive> defoltive </welcome-file-list> </web-app>
Spring Basic ConfigurationSpring.xml:
<?xml version = "1.0" encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns:p = "http://www.springframework.org/schema/p" xmlns:context = "http://www.springframework.org/schema/context" xmlns:mvc = " xsi:schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www. http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc/spring-mvc/spring <コンテキスト:annotation-config /> <mvc:annotation-driven /> <context:component-scansaber-package = "controllers" /> <! - IEがajaxを実行したときにjsonに戻ることを避けるために - > <bean id = "mappingjacksonhttpmessageconverter" mappingjacksonhttpmessageconverter " <value> text/html; charset = utf-8 </value> </list> </property> </bean> <! - スプリングMVCアノテーション関数がリクエストと注釈のマッピングを完了することを可能にするためにPojos-> <bean> <プロパティ名= "MessageConverters"> <ref bean = "Mappingjacksonhtpmester"/<コンバーター - > </list> </property> </bean> <! - ファイルのアップロードをサポート - > <bean id = "multipartresolver"> <! - > <プロパティ名= "maxuploadsize" value = "104857600"> </財産> <プロパティ名= "defally defollting" "utf-8"> </bean> </bean>
2。ファイルアップロードコード
アップロードされたSimple Page Index.htmlの場合、フォームフォームを送信するときに、ENTYPEの設定に注意してください。
<!doctype html> <html> <head> <meta http-equiv = "content-type" content = "text/html; charset = utf-8"/> </head> <body> <form action = "./ uploadfile.do" method = "post" enctype = "ファイル="ファイル ">"> "ファイル"ファイル " <入力型= "submit" value = "submit"/> </form> </body> </html>
対応するバックグラウンドJavaコードをアップロードします。特定の質問については、コメントを参照してください。
パッケージコントローラー。 java.io.fileをインポートします。 java.io.ioexceptionをインポートします。 java.util.iteratorをインポートします。 javax.servlet.http.httpservletrequestをインポートします。 org.apache.commons.io.fileutilsをインポートします。 Import org.springframework.http.httpheaders; Import org.springframework.http.httpstatus; org.springframework.http.mediatypeをインポートします。 org.springframework.http.responseentityをインポートします。 org.springframework.stereotype.controllerをインポートします。 org.springframework.web.bind.annotation.requestmappingをインポートします。 org.springframework.web.bind.annotation.RequestMethodをインポートします。 Import org.springframework.web.bind.annotation.RequestParam; Import org.springframework.web.multipart.multipartfile; Import org.springframework.web.multipart.multiparthttpservletrequest; Import org.springframework.web.multipart.commons.commonsmultipartresolver; @controller public class filecontroller { /** * file upload * * @author:tuzongxun * @title:uploadfile * @param @param file * @param @param request * @param @throw @RequestMapping(value = "/uploadfile.do"、method = requestmethod.post)public void uploadfile(httpservletrequest request)IllegalStateexception、ioexception {// @requestparam( "file")Multipartfile file = multtresolterver = multipartresolver(new new new new commonverver request.getSession()。getServletContext()); //リクエストにファイルアップロードがあるかどうか、つまり(MultiPartresolver.ismultipart(request)){// MultiParthttpservletRequestに変換されたMultiParthttservletrequest =(Multiparthttpservletrequest)request; //リクエストですべてのファイル名を取得しますiterator <string> iter = multirequest.getFileNames(); while(iter.hasnext()){//アップロードされたファイルmultipartfile f = multirequest.getFile(iter.next()); if(f!= null){//現在アップロードされているファイル文字列myfileName = f.getoriginalfileName();のファイル名を取得します。 //名前が「」でない場合、ファイルが存在することを意味します。そうでなければ、ファイルが存在しないことを意味します(myfilename.trim()!= ""){//アップロードパス文字列パス= "C://ユーザー// tuzongxun123 // desktop //" + myfilename;ファイルlocalfile = new file(path); f.transferto(localfile); }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}送信するファイルを選択した後、選択したファイルがコード内の指定された場所に渡されることがわかります。ページレンダリングは次のとおりです
3。ファイルのダウンロード
ファイルのダウンロードには、ダウンロードされたファイルのストレージパスが必要です。これは手動で記入されています。特定のプロジェクトにある場合は、データベースにファイル名とアップロードされたストレージパスを保存できます。次に、ファイルリストのページを追加してファイル名とファイルパスを表示し、クリックして、ダウンロード時に対応するファイル名とバックグラウンド操作へのパスをアップロードします。
/ **ファイルのダウンロード、ファイル名とファイルアドレスが必要 * * @author:tuzongxun * @title: @download * @param @param name * @param @param @return * @param @throws ioexception * @returnresponseentity "/downloadfile.do")public ResponseNtity <byte []> download(@RequestParam( "name")string name、@RequestParam( "filepath")string path)throws ioexception {file file = new file(path); httpheaders headers = new httpheaders(); string filename = new String(name.getBytes( "utf-8")、 "iso-8859-1"); //文字化けされた中国名name headers.setcontentdispositionformdata( "attachment"、filename)の問題を解決するため。 headers.setContentType(mediatype.application_octet_stream); new ResponseNtity <byte []>(fileutils.readfiletobytearray(file)、headers、httpstatus.created); } HTMLページは、ファイル名とファイルパスの単純な入力に過ぎず、フォームフォームを使用して背景に送信します。その後、背景は、ページにファイルパスポップアップを保存するための選択ボックスへの応答を制御します。もちろん、私はここでバックグラウンドで何もしませんでした。ファイルが存在しない場合、エラーが報告されます。対応する処理を実行できます。
ファイルのダウンロード:
</br> </br> <form action = "./ downloadfile.do" style = "border:1px solid gray; width:auto;" method = "post">ファイル名:<入力タイプ= "テキスト" name = "name"/> </br> </br> </br>ファイルパス:<入力タイプ= "テキスト" name = "filepath"/> </br> </br> <入力タイプ= "submit" value = "confism download"/> </form>
ページビューは次のとおりです。
ファイルが存在しない場合、エラーは次のとおりです。
上記はこの記事に関するものです。すべての人の学習に役立つことを願っています。