一:導入相關Jar包
commons-fileupload.jar
commons-io.jar
二:配置web.xml。上載解析器
<!-- 文件上傳配置 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 設置編碼格式 -->
<property name="defaultEncoding" value="utf-8"></property>
<!-- 設置文件大小 -->
<property name="maxUploadSize" value="10485760000"></property>
<!-- 設置緩衝區大小 -->
<property name="maxInMemorySize" value="40960"></property>
</bean>
三:web頁面
<form action="upload.do" enctype="multipart/form-data" method="post">
文件:<input type="file" name="file"/><input type="submit" value="上傳"/>
</form>
四:controller類 @RequestParam("file") 這個註解必須有
/**
* spring mvc封裝了上傳文件 將其封裝爲一個file對象
* */
@RequestMapping("/upload.do")
public String upload(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest req){
//獲取上傳位置
String path=req.getRealPath("/upload");
//獲取文件名
String filename=file.getOriginalFilename();
try {
InputStream is = file.getInputStream();
OutputStream os = new FileOutputStream(new File(path,filename));
int len=0;
byte[] buffer = new byte[400];
while((len=is.read(buffer))!=-1){
os.write(buffer, 0, len);
}
os.close();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:index.jsp";
}
五:批量上傳web頁面
<form action="batch.do" enctype="multipart/form-data" method="post">
文件1:<input type="file" name="file"/><br>
文件2:<input type="file" name="file"/><br>
<input type="submit" value="上傳"/>
</form>
六:批量上傳controller類
@RequestMapping("/batch.do")
public String batch(@RequestParam("file") CommonsMultipartFile file[],HttpServletRequest req){
//獲取上傳位置
String path=req.getRealPath("/upload");
for(int i=0;i<file.length;i++){
//獲取文件名
String filename=file[i].getOriginalFilename();
try {
InputStream is = file[i].getInputStream();
OutputStream os = new FileOutputStream(new File(path,filename));
int len=0;
byte[] buffer = new byte[400];
while((len=is.read(buffer))!=-1){
os.write(buffer, 0, len);
}
os.close();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return "redirect:index.jsp";
}