SpringMVC上傳文件的簡單實例
SpringMVC上傳文件的簡單實例
在使用springMVC進行系統(tǒng)實現(xiàn)時,springMVC默認(rèn)的解析器里面是沒有加入對文件上傳的解析的,這可以方便我們實現(xiàn)自己的文件上傳。但如果你想使用springMVC對文件上傳的解析器來處理文件上傳的時候就需要在spring的applicationContext里面加上springMVC提供的MultipartResolver的申明。這樣之后,客戶端每次進行請求的時候,springMVC都會檢查request里面是否包含多媒體信息,如果包含了就會使用MultipartResolver進行解析,springMVC會使用一個支持文件處理的MultipartHttpServletRequest來包裹當(dāng)前的HttpServletRequest,然后使用MultipartHttpServletRequest就可以對文件進行處理了。Spring已經(jīng)為我們提供了一個MultipartResolver的實現(xiàn),我們只需要拿來用就可以了,那就是org.springframework.web.multipart.commons.CommsMultipartResolver。因為springMVC的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)沒有指定的時候根據(jù)Servlet規(guī)范會使用默認(rèn)值ISO-8859-1。當(dāng)request自己指明了它的編碼格式的時候就會忽略這里指定的defaultEncoding。
uploadTempDir:設(shè)置上傳文件時的臨時目錄,默認(rèn)是Servlet容器的臨時目錄。
maxUploadSize:設(shè)置允許上傳的最大文件大小,以字節(jié)為單位計算。當(dāng)設(shè)為-1時表示無限制,默認(rèn)是-1。
maxInMemorySize:設(shè)置在文件上傳時允許寫到內(nèi)存中的最大值,以字節(jié)為單位計算,默認(rèn)是10240。
下面是一個簡單示例:
.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)要同時上傳多個文件時,可以給定多個MultipartFile參數(shù)
if (!file.isEmpty()) {
byte[] bytes = file.getBytes();
// store the bytes somewhere
//在這里就可以對file進行處理了,可以根據(jù)自己的需求把它存到數(shù)據(jù)庫或者服務(wù)器的某個文件夾
return "redirect:uploadSuccess";
} else {
return "redirect:uploadFailure";
}
}
}
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
關(guān)于JSP用戶登錄連接數(shù)據(jù)庫詳情
這篇文章主要介紹了關(guān)于JSP用戶登錄連接數(shù)據(jù)庫的相關(guān)資料,需要的朋友可以參考下面文章內(nèi)容2021-09-09
jsp+mysql實現(xiàn)網(wǎng)頁的分頁查詢
這篇文章主要為大家詳細(xì)介紹了jsp+mysql實現(xiàn)網(wǎng)頁的分頁查詢,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02
jsp session.setAttribute()和session.getAttribute()用法案例詳解
這篇文章主要介紹了jsp session.setAttribute()和session.getAttribute()用法案例詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08

