下文是SpringMVC上傳文件的簡(jiǎn)單實(shí)例,本文的介紹非常適用于SSM框架,下面是錯(cuò)新技術(shù)頻道小編為大家?guī)淼慕榻B,一起進(jìn)入下文來學(xué)習(xí)吧!
SpringMVC上傳文件的簡(jiǎn)單實(shí)例
在使用springMVC進(jìn)行系統(tǒng)實(shí)現(xiàn)時(shí),springMVC默認(rèn)的解析器里面是沒有加入對(duì)文件上傳的解析的,這可以方便我們實(shí)現(xiàn)自己的文件上傳。但如果你想使用springMVC對(duì)文件上傳的解析器來處理文件上傳的時(shí)候就需要在spring的applicationContext里面加上springMVC提供的MultipartResolver的申明。這樣之后,客戶端每次進(jìn)行請(qǐng)求的時(shí)候,springMVC都會(huì)檢查request里面是否包含多媒體信息,如果包含了就會(huì)使用MultipartResolver進(jìn)行解析,springMVC會(huì)使用一個(gè)支持文件處理的MultipartHttpServletRequest來包裹當(dāng)前的HttpServletRequest,然后使用MultipartHttpServletRequest就可以對(duì)文件進(jìn)行處理了。Spring已經(jīng)為我們提供了一個(gè)MultipartResolver的實(shí)現(xiàn),我們只需要拿來用就可以了,那就是org.springframework.web.multipart.commons.CommsMultipartResolver。因?yàn)閟pringMVC的MultipartResolver底層使用的是Commons-fileupload,所以還需要加入對(duì)Commons-fileupload.jar的支持。
Xml代碼
<!-- 這里申明的id必須為multipartResolver --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- one of the properties available; the maximum file size in bytes --> <property name="maxUploadSize" value="100000"/> </bean>
CommonsMultipartResolver允許設(shè)置的屬性有:
?? ? defaultEncoding:表示用來解析request請(qǐng)求的默認(rèn)編碼格式,當(dāng)沒有指定的時(shí)候根據(jù)Servlet規(guī)范會(huì)使用默認(rèn)值ISO-8859-1。當(dāng)request自己指明了它的編碼格式的時(shí)候就會(huì)忽略這里指定的defaultEncoding。
??? uploadTempDir:設(shè)置上傳文件時(shí)的臨時(shí)目錄,默認(rèn)是Servlet容器的臨時(shí)目錄。
??? maxUploadSize:設(shè)置允許上傳的最大文件大小,以字節(jié)為單位計(jì)算。當(dāng)設(shè)為-1時(shí)表示無限制,默認(rèn)是-1。
??? maxInMemorySize:設(shè)置在文件上傳時(shí)允許寫到內(nèi)存中的最大值,以字節(jié)為單位計(jì)算,默認(rèn)是10240。?
下面是一個(gè)簡(jiǎn)單示例:
.html文件
<html> <head> <title>Upload a file please</title> </head> <body> <h1>Please upload a file</h1> <!-- enctype(編碼格式)必須為multipart/form-data --> <form method="post" action="/form" enctype="multipart/form-data"> <input type="text" name="name"/> <input type="file" name="file"/> <input type="submit"/> </form> </body> </html>
對(duì)應(yīng)的action controller:
Java代碼
@Controller public class FileUpoadController { @RequestMapping(value = "/form", method = RequestMethod.POST) public String handleFormUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) { //MultipartFile是對(duì)當(dāng)前上傳的文件的封裝,當(dāng)要同時(shí)上傳多個(gè)文件時(shí),可以給定多個(gè)MultipartFile參數(shù) if (!file.isEmpty()) { byte[] bytes = file.getBytes(); // store the bytes somewhere //在這里就可以對(duì)file進(jìn)行處理了,可以根據(jù)自己的需求把它存到數(shù)據(jù)庫或者服務(wù)器的某個(gè)文件夾 return "redirect:uploadSuccess"; } else { return "redirect:uploadFailure"; } } } 以上就是由錯(cuò)新技術(shù)頻道小編為大家?guī)淼腟pringMVC上傳文件的簡(jiǎn)單實(shí)例,希望對(duì)大家有所幫助!如果你還不知道這些知識(shí),那么趕快學(xué)習(xí)吧!
新聞熱點(diǎn)
疑難解答
圖片精選