SpringMVC-12-檔案上傳和下載
-
前端要求
-
將表單的method設定為POST
-
將enctype設定為multipart/form-data
表單中的 enctype 屬性
-
application/x-www=form-urlencoded
預設方式,只處理表單域中的 value 屬性值,採用這種編碼方式的表單會將表單域中的值處理成 URL 編碼方式
-
multipart/form-data
這種編碼方式會以二進位制流的方式來處理表單資料,這種編碼方式會把檔案域指定檔案的內容也封裝到請求引數中,不會對字元編碼
-
text/plain
除了把空格轉換為 "+" 號外,其他字元都不做編碼處理,這種方式適用直接通過表單傳送郵件
-
-
一旦設定了enctype為multipart/form-data,瀏覽器會採用二進位制流的方式來處理表單資料
SpringMVC為檔案上傳提供了直接的支援,用即插即用的MultipartResolver實現的
SpringMVC使用Apache Commons FileUpload技術實現了一個MultipartResolver的實現類:CommonsMultipartResolver
-
CommonsMultipartFile 的 常用方法
-
String getOriginalFilename():獲取上傳檔案的原名
-
InputStream getInputStream():獲取檔案流
-
void transferTo(File dest):將上傳檔案儲存到一個目錄檔案中
-
2、檔案上傳
-
1、匯入依賴
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<version>2.5</version>
</dependency> -
配置bean
<!--檔案上傳配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 請求的編碼格式,必須和jSP的pageEncoding屬性一致,以便正確讀取表單的內容,預設為ISO-8859-1 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 上傳檔案大小上限,單位為位元組(10485760=10M) -->
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean> -
編寫前端頁面
<%
-
Controller:方式一
-
Controller:方式二,採用file.Transto 來儲存上傳的檔案
3、檔案下載
-
步驟
-
1、設定 response 響應頭
-
2、讀取檔案 -- InputStream
-
3、寫出檔案 -- OutputStream
-
4、執行操作
-
5、關閉流 (先開後關)
-
-
前端頁面編寫
<a href="/download">點選下載</a>
-
Controller
public String downloads(HttpServletResponse response ,HttpServletRequest request) throws Exception{
//要下載的圖片地址
String path = request.getServletContext().getRealPath("/upload");
String fileName = "基礎語法.jpg";
//1、設定response 響應頭
response.reset(); //設定頁面不快取,清空buffer
response.setCharacterEncoding("UTF-8"); //字元編碼
response.setContentType("multipart/form-data"); //二進位制傳輸資料
//設定響應頭
response.setHeader("Content-Disposition",
"attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));
File file = new File(path,fileName);
//2、 讀取檔案--輸入流
InputStream input=new FileInputStream(file);
//3、 寫出檔案--輸出流
OutputStream out = response.getOutputStream();
byte[] buff =new byte[1024];
int index=0;
//4、執行 寫出操作
while((index= input.read(buff))!= -1){
out.write(buff, 0, index);
out.flush();
}
out.close();
input.close();
return null;
}