SpringMVC上傳文件的簡單實(shí)例
在使用springMVC進(jìn)行系統(tǒng)實(shí)現(xiàn)時(shí),springMVC默認(rèn)的解析器里面是沒有加入對文件上傳的解析的,這可以方便我們實(shí)現(xiàn)自己的文件上傳。但如果你想使用springMVC對文件上傳的解析器來處理文件上傳的時(shí)候就需要在spring的applicationContext里面加上springMVC提供的MultipartResolver的申明。這樣之后,客戶端每次進(jìn)行請求的時(shí)候,springMVC都會(huì)檢查request里面是否包含多媒體信息,如果包含了就會(huì)使用MultipartResolver進(jìn)行解析,springMVC會(huì)使用一個(gè)支持文件處理的MultipartHttpServletRequest來包裹當(dāng)前的HttpServletRequest,然后使用MultipartHttpServletRequest就可以對文件進(jìn)行處理了。Spring已經(jīng)為我們提供了一個(gè)MultipartResolver的實(shí)現(xiàn),我們只需要拿來用就可以了,那就是org.springframework.web.multipart.commons.CommsMultipartResolver。因?yàn)閟pringMVC的MultipartResolver底層使用的是Commons-fileupload,所以還需要加入對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請求的默認(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è)簡單示例:
.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>
對應(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是對當(dāng)前上傳的文件的封裝,當(dāng)要同時(shí)上傳多個(gè)文件時(shí),可以給定多個(gè)MultipartFile參數(shù) if (!file.isEmpty()) { byte[] bytes = file.getBytes(); // store the bytes somewhere //在這里就可以對file進(jìn)行處理了,可以根據(jù)自己的需求把它存到數(shù)據(jù)庫或者服務(wù)器的某個(gè)文件夾 return "redirect:uploadSuccess"; } else { return "redirect:uploadFailure"; } } } 感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選