次のように、スプリングMVCファイルのアップロードとダウンロード:
(1)JARパッケージのインポート:ant.jar、commons-fileupload.jar、connom-io.jar。
(2)src/context/dispatcher.xmlを追加します
<bean id = "multipartresolver" p:defaultencoding = "utf-8" />
追加した後に以下に示すように、頭にコンテンツを追加する必要があることに注意してください。
<beans default-lazy-init = "true" xmlns = "http://www.springframework.org/schema/beans" xmlns:p = "http://www.springframework.org/schema/p" xmlns:xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns:context = "http://www.springframework.org/schema/context" XMLNS:MVC = "http://www.springframework.org/schema/mvc" xsi:schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.sspringframework/ http://www.springframework.org/schema/context/spring-context-3.0.xsd ">
(3)ツールクラスFileOpereTil.javaを追加します
/ ** * * @author geoin */ package com.geloin.spring.util; java.io.bufferedinputStreamをインポートします。 java.io.bufferedOutputStreamをインポートします。 java.io.fileをインポートします。 java.io.fileinputStreamをインポートします。 java.io.fileoutputStreamをインポートします。 java.text.simpledateformatをインポートします。 java.util.arraylistをインポートします。 Import Java.util.date; java.util.hashmapをインポートします。 java.util.iteratorをインポートします。 java.util.listをインポートします。 java.util.mapをインポートします。 javax.servlet.http.httpservletrequestをインポートします。 javax.servlet.http.httpservletResponseをインポートします。 org.apache.tools.zip.zipentryをインポートします。 import org.apache.tools.zip.zipoutputStream; org.springframework.util.filecopyutilsをインポートします。 Import org.springframework.web.multipart.multipartfile; Import org.springframework.web.multipart.multiparthttpservletrequest; public class fileOpereTil {private static final string realname = "realname"; private static final string storename = "storename";プライベート静的最終文字列サイズ= "サイズ"; private static final string suffix = "suffix"; private static final string contentType = "contentType"; private static final string createTime = "CreateTime"; private static final string uploaddir = "uploaddir/"; / ** *アップロードされたファイルの名前を変更 * * @param name * @return */ private static string rename(string name){long now = long.parselong(new simpledateformat( "yyyymmddhhmmss").format(new date())); long random =(long)(math.random() * now);文字列filename = now + "" + random; if(name.indexof( "。")!= -1){filename += name.substring(name.lastindexof( "。")); } filenameを返します。 } / ** *圧縮ファイル名 * * @param name * @return * / private static string zipname(string name){string prefix = ""; if(name.indexof( "。")!= -1){prefix = name.substring(0、name.lastindexof( "。")); } else {prefix = name; } prefix + ".zip"を返します。 } / ** * upload file * * @param request * @param params * @param values * @return * @throws例外 * / public static list <map <string、object >> upload(httpservletrequest request、string [] params、map <string、obje。 MultiParthTTPSERVLETREQUEST MREQUEST =(MultiParthTTPSERVLETREQUEST)リクエスト; map <string、multipartfile> filemap = mrequest.getFileMap(); string uploaddir = request.getSession()。getServletContext().getRealPath( "/") + fileOpereTil.uploaddir; file file = new file(uploadDir); if(!file.exists()){file.mkdir(); }文字列filename = null; int i = 0; for(iterator <map.entry <string、multipartfile >> it = filemap.entryset().iterator(); it.hasnext(); i ++){map.entry <string、multipartfile> entry = it.next(); multipartfile mfile = entry.getValue(); filename = mfile.getoriginalfilename();文字列storeName = rename(filename);文字列nozipname = uploaddir + storeName; string zipname = zipname(nozipname); //アップロードして圧縮ファイルになりますzipoutputStream outputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(ZIPNAME))); outputStream.putNextEntry(new Zipentry(filename)); outputStream.SetEncoding( "GBK"); filecopyutils.copy(mfile.getinputStream()、outputStream); map <string、object> map = new hashmap <string、object>(); //パラメーター値を固定したペアマップ。 map.put(fileoperateutil.storename、zipname(storename)); map.put(fileperetyutil.size、new file(zipname).length()); map.put(fileoperateutil.suffix、 "zip"); map.put(fileperetyutil.contentType、 "Application/Octet-Stream"); map.put(fileopereTutil.createtime、new date()); //(string param:params){map.put(param、values.get(param)[i]); } result.add(map); } return result; } / ** *ダウンロード * @param request * @param Response * @param StoreName * @Param ContentType * @Param RealName * @Throws Exception * / public Static Void Download(httpservletResponse Response、httpservletResponse Response、httpsers storeName、string contentType、string realName){ Response.setContentType( "text/html; charset = utf-8"); request.setcharacterencoding( "utf-8"); bufferedinputStream bis = null; BufferedOutputStream bos = null; string ctxpath = request.getSession()。getServletContext().getRealPath( "/") + fileOpereTil.uploaddir;文字列downloadpath = ctxpath + storename; long filelength = new file(downloadpath).length(); Response.setContentType(contentType); Response.setheader( "content-disposition"、 "attachment; filename =" + new String(realname.getBytes( "utf-8")、 "ISO8859-1")); Response.setheader( "content-length"、string.valueof(filelength)); bis = new BufferedInputStream(new FileInputStream(downloadPath)); bos = new BufferedOutputStream(respons.getOutputStream()); byte [] buff = new byte [2048]; int bytesRead; while(-1!=(bytesRead = bis.read(buff、0、buff.length))){bos.write(buff、0、bytesread); } bis.close(); bos.close(); }}クラスを変更せずに完全に使用できます。アップロードされたファイルは、WebContent/uploadDirの下に配置されていることに注意してください。
(4)FileOperateController.javaを追加します
/ ** * * @author geoin */ package com.geloin.spring.controller; java.util.hashmapをインポートします。 java.util.listをインポートします。 java.util.mapをインポートします。 javax.servlet.http.httpservletrequestをインポートします。 javax.servlet.http.httpservletResponseをインポートします。 org.springframework.stereotype.controllerをインポートします。 org.springframework.web.bind.servletrequestutilsをインポートします。 org.springframework.web.bind.annotation.requestmappingをインポートします。 Import org.springframework.web.servlet.modelandview; com.geloin.spring.util.fileoperateutilをインポートします。 @Controller @RequestMapping(value = "background/fileoperate")public class fileoperatecontroller {/***ファイルがアップロードされる場所へ* @return*/@requestmapping(value = "to_upload")public modelandview toupload() } / ** * upload file * * @param request * @return * @throws例外 * / @requestMapping(value = "upload")public modelandview upload(httpservletrequest request)スロー{map <string、object> map = new hashmap <string、object>(); // alias string [] alaises = servletrequestutils.getStringParameters(request、 "alais"); string [] params = new String [] {"Alais"}; map <string、object []> values = new hashmap <string、object []>(); Value.put( "Alais"、Alaises); List <Map <String、Object >> result = fileOpereTutil.upload(request、params、values); map.put( "result"、result); new ModelandView( "background/fileoperate/list"、map)を返します。 } / ** *ダウンロード * * @param attachment * @param request * @param response * @param Response * @return * @Throws Exception * / @RequestMapping(value = "download")public ModelandView Download(httpservletrequest request、httpservletResponse応答)スロー例外{string storeName = " string realname = "java design pattern.zip"; string contentType = "Application/Octet-Stream"; fileOpereTutil.download(request、response、storeName、contentType、realName); nullを返します。 }}ダウンロード方法を自分で変更してください。データベースを使用してアップロードされたファイル情報を保存する場合は、Spring MVC Integration MyBatisインスタンスを参照してください。
(5)FileOperate/upload.jspを追加します
<%@ページ言語= "java" contentType = "text/html; charset = utf-8" pageencoding = "utf-8"%> <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core"トランジショナル// en "" http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd "> <html> <hed> <meta http-equiv =" content-type "content =" text/html; < /body> <form enctype = "multipart /form-data" action = "<c:url value =" /background /fileoperate /upload.html " />" methed = "post"> <input type = "file" name = "file1" />> <inputタイプ= "テキストname =" alais " />> <入力タイプ="ファイル "ファイル"ファイル= "ファイル="ファイルname = "alais" /> <br /> <入力タイプ= "file" name "name =" file3 " /> <入力タイプ=" text "name =" alais " /> <br /> <入力タイプ=" submit "value =" upload " /> < /form> < /html> < /html>
Enctype値がMultiPart/Form-Dataであることを確認してください。メソッド値はpostです。
(6)FileOperate/list.jspを追加します
<%@ページ言語= "java" contentType = "text/html; charset = utf-8" pageencoding = "utf-8"%> <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core"トランジショナル// en "" http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd "> <html> <hed> <meta http-equiv =" content-type "content =" text/html; <c:foreach items = "$ {result}" var = "item"> <c:foreachアイテム= "$ {item}" var = "m"> <c:if test = "$ {m.key eq '' realname '}"> $ {m.value} </c:if> <br/> </c:foreach> </c:</c:(7)http:// localhost:8080/spring_test/background/fileoperate/to_upload.htmlを介してアップロードページにアクセスし、http:// localhost:8080/spring_test/background/fileoperate/download.htmlを介してファイルをダウンロードします。
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。