一、單檔案上傳
1. 導入新增的jar包
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
2. 配置spring mvc檔案上傳解析器
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1048576000"></property>
<property name="defaultEncoding" value="utf-8"></property>
</bean>
3. Jsp界面
<form action="upload.do" method="post" enctype="multipart/form-data">
file:<input type="file" name="file"/>
<input type="submit" value="上傳"/>
</form>
4. Controller控制器處理類
@RequestMapping("/upload")
public String upload(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest req) throws IOException {
// 擷取upload檔案的路徑
String path = req.getRealPath("upload");
InputStream is = file.getInputStream();
OutputStream os = new FileOutputStream(new File(path,file.getOriginalFilename()));
int len = ;
byte[] buffer = new byte[];
// is.read(buffer)讀取檔案寫入buffer數組位元組 ,約定讀
//取檔案結束為-1,首先指派給len(要看具體環境
// 一般約定-1為讀結束,-2為都出錯,此處也可設定為<0)
while((len=is.read(buffer))!=-) {
// 檔案未結束
// 指定從指定的位元組數開始到輸出流關閉寫入len長度位元組
// os.write(byte,off(資料偏移開始量),len(寫入的位元組數));
os.write(buffer, , len);
}
os.close();
is.close();
return "index.jsp";
}
5. 測試
輸入請求url,并上傳檔案:
在tomcat裡找到響應的項目
在upload中可以看到此檔案
二、檔案批量上傳
與上文1、2點相同;
3.jsp界面
<form action="batch.do" method="post" enctype="multipart/form-data">
file:<br>
<input type="file" name="file"/><br><br>
<input type="file" name="file"/><br><br>
<input type="file" name="file"/><br><br>
<input type="file" name="file"/><br><br>
<input type="submit" value="上傳"/>
</form>
4.控制器處理類
@RequestMapping("/batch")
public String upload(@RequestParam("file") CommonsMultipartFile file[],HttpServletRequest req) throws IOException {
System.out.println("start");
// 擷取upload檔案的路徑
String path = req.getRealPath("upload");
for (int i = ; i < file.length; i++) {
InputStream is = file[i].getInputStream();
OutputStream os = new FileOutputStream(new File(path,file[i].getOriginalFilename()));
int len = ;
byte[] buffer = new byte[];
// is.read(buffer)讀取檔案寫入buffer數組位元組 ,約定讀取檔案結束為-1,首先指派給len(要看具體環境
// 一般約定-1為讀結束,-2為都出錯,此處也可設定為<0)
while((len=is.read(buffer))!=-) {
// 檔案未結束
// 指定從指定的位元組數開始到輸出流關閉寫入len長度位元組
// os.write(byte,off(資料偏移開始量),len(寫入的位元組數));
os.write(buffer, , len);
}
os.close();
is.close();
}
return "batch.jsp";